简体   繁体   中英

join 3 mysql tables with condition

im having 3 tables

product
-product_id
-name
-image

product_description
-product_id
-product_description
-product_attributes

product_store
-product_id
-store_id

what i need to do is get the product name, description and image from the product and product_description tables and the products should be only from the product_store table where the store_id = 0 or 1 .

the product_store table has only the product_id and store_id fields

so far i have joined the product and product_description tables. But im still trying to join the product_store table to check if the products comes from the correct store.

SELECT p.product_id, pd.name,p.image FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) order by p.product_id DESC LIMIT 3

can anyone tell me how can i join the 3rd table and check if its from the correct store_id?

select distinct p.product_id, d.name, p.image
from product p join product_description d on
  p.product_id = d.product_id join product_store s on
  p.product_id = s.product_id
where
  s.store_id in (0, 1)
order by p.product_id DESC LIMIT 3

The DISTINCT is necessary as you might join with product_store twice, and duplicate rows.

Add the 3rd table in the party (I mean JOIN), like this:

SELECT p.product_id, pd.name,p.image 
FROM product p 
LEFT JOIN product_description pd 
ON (p.product_id = pd.product_id)
JOIN product_store ps
ON (p.product_id = ps.product_id AND ps.store_id IN (0,1))
ORDER BY p.product_id DESC 
LIMIT 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM