我是mysql的新手。这是我的db表的结构。*如何加入所有三个表来提供看起来像第四个表的结果?
表产品
id name category user_id
1 abc 2 1
2 syz 3 1
表类别
id name
1 aaa
2 bbb
3 ccc
表product_image
id image product_id
1 abc.jpg 1
2 xyz.jpg 1
Forth表结果看起来像
id name category_name image
1 abc aaa xyz.jpg
请帮我解决这个问题。我试过但没有得到正确的结果。
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
编辑部分
我们需要来自product_image的一张图片,该图片根据product_id
关联多个图片答案 0 :(得分:5)
试试这个
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
答案 1 :(得分:0)
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
答案 2 :(得分:0)
试试这个
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
答案 3 :(得分:0)
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'