我有3张桌子
分类
category_id int(11) auto increment PK
name varchar(100)
产品
category_id int(11) FK from increment
product_id int(11) auto increment PK
Name varchar(100)
收藏
favourite_id int(11) auto increment PK
product_id int(11) FK from product
user_id int(11) FK from user
我想要数据所有产品name, category name, favourite = 1
如果记录存在于收藏表中,则其他0为特定用户
答案 0 :(得分:0)
您可以尝试类似
的内容SELECT p.`name` , c.name AS categoryName , IFNULL(f.user_id,0), IFNULL(f.product_id ,0)
FROM Category c INNER JOIN Product p
ON c.category_id = p.category_id
LEFT JOIN Favourite f
ON f.product_id =p.product_id
答案 1 :(得分:0)
只需使用LEFT JOIN:
SELECT A.Name Product_Name, B.Name Category_Name
FROM Product A LEFT JOIN Category B
ON A.category_id=B.category_id
LEFT JOIN Favourite C
ON A.product_id=C.product_id
WHERE favourite_id=1;
答案 2 :(得分:0)
尝试此操作,$user_id
用于特定用户
SELECT p.Name as product_name, c.Name as Category_name
FROM Product p
JOIN Category c ON p.category_id=c.category_id
JOIN Favourite f ON p.product_id=f.product_id
WHERE f.user_id= '$user_id';