[英]Check if ID exist in another table if yes return TRUE
I have a grocery Database, Grocery Items Belongs to Category or To a Sub Category and can be part of Favourite List 我有一个杂货数据库,杂货项目属于类别或子类别,可以成为收藏列表的一部分
When I am reading the list of Items from the Category, I would like to include a boolean value to see if the item is part of Favourite list. 当我从类别中读取项目列表时,我想包含一个布尔值,以查看该项目是否是收藏夹列表的一部分。
Favourite is stored as a combination of Product_ID and USER_ID with a Primary key index id 收藏夹存储为Product_ID和USER_ID与主键索引ID的组合
I have been failed to make the left join for favourite list. 我没有把左边的连接列为最喜欢的列表。
Would really appreciate your support. 非常感谢您的支持。
Database with data https://wetransfer.com/downloads/853bd65b90f3a36b4d9264c018bbda9720190409083930/7d620e 带数据的数据库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
I didn't get the meaning of retrieving the two 'count columns'. 我没有得到检索两个'计数列'的含义。 But, still if you just need favourite of user 1 or not, you can use FavouriteOrNot column from this query:
但是,如果您只是需要用户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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.