检查ID是否存在于另一个表中,如果是,则返回TRUE

时间:2019-04-09 08:23:44

标签: mysql sql

我有一个杂货数据库,杂货项目属于类别或子类别,并且可以成为收​​藏夹列表的一部分

当我从“类别”中读取项目列表时,我想包含一个布尔值,以查看该项目是否是“收藏夹”列表的一部分。

收藏夹以Product_ID和USER_ID的组合存储,并具有主键索引ID

我未能加入最爱列表的左联接。

非常感谢您的支持。

具有数据的数据库 https://wetransfer.com/downloads/853bd65b90f3a36b4d9264c018bbda9720190409083930/7d620e


    Select a.*, ifnull(Deriv1.Count , 0) as Count, ifnull(Total1.PCount, 0) as PCount FROM `categories` a  
LEFT OUTER JOIN (SELECT `parent`, COUNT(*) AS Count FROM `categories` GROUP BY `parent`) Deriv1 ON a.`id` = Deriv1.`parent` 
LEFT OUTER JOIN (SELECT `category_id`,COUNT(*) AS PCount, 
JOIN (SELECT id From Favorite Where userID='1' )  FROM `products` GROUP BY `category_id`) Total1 ON a.`id` = Total1.`category_id` 
WHERE a.`parent`=" . $parent


1 个答案:

答案 0 :(得分:0)

我没有获取两个“计数列”的含义。但是,即使您是否只需要用户1的收藏夹,也可以在此查询中使用FavouriteOrNot列:

SELECT p.product_id, a.id, f.userID, IFNULL(Deriv1.Count , 0) as Count, IFNULL(Total1.PCount, 0) as PCount, IFNULL(f.id, 0) as FavouriteOrNot 
FROM 
`products` p 
INNER JOIN 
`categories` a 
ON 
p.`category_id` = a.`id` 
LEFT OUTER JOIN 
(SELECT `parent`, COUNT(*) AS Count FROM `categories` GROUP BY `parent`) Deriv1 
ON 
a.`id` = Deriv1.`parent` 
LEFT OUTER JOIN 
(SELECT `category_id`,COUNT(*) AS PCount FROM `products` GROUP BY `category_id`)Total1 
ON 
a.`id` = Total1.`category_id` 
LEFT OUTER JOIN 
`Favorite` f 
ON 
f.`ProductID` = p.`product_id` 
AND 
userID = 1 
WHERE a.`parent`= 1