Craig van Tonder
Craig van Tonder

Reputation: 7687

MYSQL - A little bit of trouble/confusion with join query

I am trying to put together a mysql query, that links 3 tables together. In essence, the tables are as follows:

  1. products - Contains product information and basic pricing.
  2. product_depts - Linking table that links products to different departments.
  3. promotions - Another linking table, links promotion periods and prices based on product id.

This is the query:

SELECT p.id, `desc` , price1, price2, cost1, taxable, quantity, deptId, sale
FROM products p
INNER JOIN product_depts ON p.id = prodId
INNER JOIN promotions s ON p.id = s.id
WHERE MATCH (
`desc`
)
AGAINST (
'CLOVER'
IN BOOLEAN
MODE
)
ORDER BY `desc`
LIMIT 0 , 30

If the following line is removed:

INNER JOIN promotions s ON p.id = s.id

And sale taken out of the select clause,

What happens, is ALL the products with a description containing "CLOVER", in the products table, are returned.

With the addition of the removed query parts, only the items that are on promotion (have a matching id in the promotions table), are returned. And any additional products containing "CLOVER" in the products table, that are not "on promotion" are left out.

As I have very limited knowledge with mysql, I thought maybe someone that does have a great deal of knowledge on the matter to share... Would like to provide some input with this.

As i understand it though, this would be essentially the same thing as calling deptId from the product_depts table, which works perfectly. So it is confusing me.

What am i doing wrong that only the items that are "on promotion" are displayed and the additional results are left out?

Thank you!

Upvotes: 0

Views: 43

Answers (1)

Marc B
Marc B

Reputation: 360592

INNER joins basically say "retrieve all records where there's a matching record in BOTH tables".

If I'm reading your question correctly, it sounds like what you'd want is a LEFT or RIGHT join, which translates to "retrieve all records from one table, and (if any) matching records from the other table.

Sounds like you want to get all products, whether they have a promotion or not, but if they do have a promotion, retrieve the promo info as well.

That'd be

SELECT ...
FROM products
INNER JOIN product_depts ON ...
LEFT JOIN promotions ON ...

So... all products MUST have a department, so do an inner join for that particular part of the query. The left join on promotions makes the 'products' table be the LEFT table, so all records from that table are fetched. The promotions table becomes the RIGHT table, and only provides data for the query results if there's a matching record in the promotions table.

So... given 2 products, 1 of which is on sale, you'd get

   product #1    department #1   promoinfo #1
   product #2    department #2   NULL

for results. Since there's no matching promo information for the #2 product, you get NULL for the promo data.

Upvotes: 2

Related Questions