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

标签 mysql join count group-concat

我有三张 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/

相关文章:

MYSQL 对每种可能的情况进行计数和求和

java - 如果我更改值,Android 倒计时器不工作

mysql - 查询时出现重复记录问题

SQL 数组聚合和连接

mysql - 根据最低出现值构建表和连接记录

php - 在 JOIN 查询中获取共享参数

php - 如何在返回时对从 mysql 返回的每一行进行编号

javascript - 在预定义的 Javascript 代码中导入 MySQL 表

java - 获取 http ://myserverip:8081/myapp/api/v1/campaigns 500 (Internal Server Error)

mysql - PHPMYADMIN 中的 SQL