gpt4 book ai didi

mysql - 如何使用组连接获取第三个表计数

转载 作者:行者123 更新时间:2023-11-29 12:08:24 25 4
gpt4 key购买 nike

我有三张 table 。
1) tbl_product基表//存储产品信息。

id int(11) unsigned
product_type_id int(11) unsigned
product_image varchar(255)
title varchar(255)
description text
price float(8,2)
discount_price float(8,2)
status tinyint(1)
created_at datetime
updated_at datetime

2) tbl_product_review//存储每个产品的评论。

id  int(10) unsigned
product_id int(10) unsigned
title varchar(255)
description text
star_rating int(1)
status int(1)
created_at int(10)

3) tbl_wishlist//存储用户的愿望 list 详细信息意味着当用户将任何产品添加到他/她的愿望 list 中时,该条目保存在此表中

id  int(11) unsigned
product_id int(11) unsigned
user_id int(11) unsigned
status tinyint(1) unsigned
created_at datetime

这些是我的表架构。我想根据产品 ID 使用组连接来获取用户的 ID。意味着如果产品 id 为 1,那么所有用户的 id 都会像这样出现 (1,3,4,5)。接下来是,我想要每个产品的产品评论总数。例如,如果用户 ID 为 1,则产品编号为 1,如果有或没有,则产品编号为 0。

其实我想要这种类型的输出

id  product_type_id title               description              price  discount_price       product_image      users   total_review
1 1 Product one Product one description 786 50 product.jpg 1,2 2

我想通过单个查询来完成此操作。我不想在开始循环之后获取前半部分信息,而不是获取下半部分信息。我想你明白我的问题。

最佳答案

你可以尝试像下面这样。您可以从各自的表中获取连接的用户列表和计数,然后可以将它们与基本产品JOIN以获得合并的结果。

select p.*,XX.total_review,XXX.user_list
from tbl_product p join (

select product_id, count(*) as total_review
from tbl_product_review
grup by product_id
) XX on product_id = XX.product_id
join (
select product_id,group_concat(user_id) as user_list
from tbl_wishlist
group by product_id
) XXX on p.product_id = XXX.product_id

关于mysql - 如何使用组连接获取第三个表计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com