gpt4 book ai didi

mysql - sql 没有显示正确的结果

转载 作者:可可西里 更新时间:2023-11-01 08:31:02 26 4
gpt4 key购买 nike

我在 mySql 中有以下表格。

博客

Field       Type         
---------- ------------
id int(11)
name varchar(255)
user_id int(11)
share int(14)

user_blog_analytics

Field        Type        
----------- ------------
id int(11)
blog_id int(11)
ip varchar(255)
impressions int(11)
date date

user_profile

Field        Type        
----------- ------------
id int(11)
user_id int(11)
description text
share int(14)

user_profile_analytics

Field        Type        
----------- ------------
id int(11)
user_id int(11)
ip varchar(255)
impressions int(11)
date date

用户

Field        Type        
----------- ------------
id int(11)
email varchar(255)

我想要一个查询,从 blog 表中获取每个用户的博客总份额,从 user_profile 表中获取每个用户的个人资料总份额,昨天的博客总浏览量,即来自 user_blog_analytics 表,来自 user_profile_analytics 表的个人资料的所有时间 View 。

我创建了一个查询,但没有给我预期的结果,它只给我很少的结果。

SELECT a.user_id, COUNT(DISTINCT b.ip) AS blog_view_count, a.share AS blog_share_count, c.share AS profile_share_count, COUNT(DISTINCT d.ip) AS user_profile_view
FROM blog AS a
JOIN user_blog_analytics AS b ON b.blog_id=a.id
JOIN user_profile AS c ON c.user_id=a.user_id
JOIN user_profile_analytics AS d ON d.user_id=c.user_id
JOIN users AS e ON e.id=a.user_id
WHERE DATE_SUB(CURDATE(), INTERVAL 1 DAY) = b.date AND e.role_id=2
GROUP BY a.id;

当我运行这个查询时,它只给我一个结果,但是当我手动检查表格时,它应该至少给我 2 个结果。告诉我哪里错了,我怎样才能通过修改这个查询得到结果。

最佳答案

试试这个:

SELECT u.id, u.email, b.blog_share_count, b.blog_view_count, 
up.profile_share_count, upa.user_profile_view
FROM users u
LEFT JOIN (SELECT b.user_id, SUM(b.share) AS blog_share_count, COUNT(DISTINCT b.ip) AS blog_view_count
FROM blog b
LEFT JOIN user_blog_analytics AS uba ON uba.blog_id = b.id AND DATE_SUB(CURDATE(), INTERVAL 1 DAY) = uba.date
GROUP BY b.user_id
) b ON u.id = b.user_id
LEFT JOIN (SELECT up.user_id, SUM(up.share) AS profile_share_count
FROM user_profile up
GROUP BY up.user_id
) up ON u.id = up.user_id
LEFT JOIN (SELECT up.user_id, COUNT(DISTINCT up.ip) AS user_profile_view
FROM user_profile_analytics up
GROUP BY up.user_id
) upa ON u.id = upa.user_id

关于mysql - sql 没有显示正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27377753/

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