[英]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? 我是mysql的新手。这是我的db表的结构。*如何将所有三个表连接起来以得到类似于第四个表的结果?
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 表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 我们需要product_image中的一幅图像,根据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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.