简体   繁体   中英

sql join query issue with three table

I am new to mysql.Here is the structure of my db table.*How can I join all three table to give results that look like the fourth table?

Table Product

id      name    category   user_id  
1       abc     2             1
2       syz     3             1

Table Categories

id      name
1       aaa
2       bbb
3       ccc

Table product_image

id      image       product_id
1       abc.jpg         1
2       xyz.jpg         1

Forth table result looks like

id      name      category_name           image
 1      abc       aaa                    xyz.jpg

Please help me to solve this. I tried but am not getting the correct result.

SELECT product. * , categories.name AS cat_name, product_image.image AS product_image
FROM `product`
INNER JOIN categories ON categories.id = product.category and `user_id`='1'
INNER JOIN `product_image` ON product_image.product_id = product.id
ORDER BY rand( )
LIMIT 1

EDITING PART

we need one image from product_image which is associated multiple image in according to product_id

Try this one

SELECT p.id, p.name , c.name as category_name, i.image FROM Product AS p

INNER JOIN Categories as c

ON c.id=p.category LEFT JOIN 

(SELECT image, product_id FROM product_image ORDER BY RAND( ) LIMIT 1  ) AS i   ON i.product_id=p.id WHERE p.id=1
SELECT
    p.id, p.name, p.category, p.user_id,
    c.id, c.name as cat_name,
    prod_image.image as product_image
FROM
    Product p,
    Categories c,
    product_image prod_image
WHERE
    p.user_id=1
AND
    p.category=c.id
AND
    prod_image.product_id=p.id
ORDER BY rand() LIMIT 1

try this

SELECT product.name , categories.name AS cat_name, product_image.image AS product_image
FROM `product`
 JOIN categories ON (categories.id = product.category)
 JOIN `product_image` ON product_image.product_id = product.id Where product.`user_id`='1'
ORDER BY rand( )
LIMIT 1
SELECT Product.id as Id,Product.name  as name, Categories.name as category_name    ,product_image.image as image 
FROM 
Product, Categories,product_image
WHERE
Product.ID='1' AND Categories.Id='1' AND product_image='1'

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