Re: [SQL ] 不同表格 统计

楼主: cutekid (可爱小孩子)   2018-04-27 19:17:45
问题2:
SELECT user.account, count(post.id) AS post_num
FROM user, post
WHERE user.id = post.user_id AND post.post_time = '2018-04-27'
GROUP BY post.user_id,user.data_order
ORDER BY user.data_order
注: order by user.data_order ←需在 group by 同时也加上 user.data_order
问题3:
SELECT user.account, count(post.id) AS post_num
FROM user
LEFT JOIN post on user.id = post.user_id
where post.post_time = '2018-04-27'
GROUP BY post.user_id,user.data_order
ORDER BY user.data_order
上面这样写,结果会等价于问题 2 的解法
但如果改成以下写法(注意黄色部份):
SELECT user.account, count(post.id) AS post_num
FROM user
LEFT JOIN post on user.id = post.user_id and post.post_time = '2018-04-27'
GROUP BY post.user_id,user.data_order
ORDER BY user.data_order
结果不一定会一样唷!
所以用 LEFT JOIN 的时候,要很清楚知道自己想要的是什么唷!
对了,LEFT JOIN 效能不会比较好唷!
※ 引述《lazior (懒人)》之铭言:
: 数据库名称:mysql
: 数据库版本:
: 内容/问题描述:
: 有两个表格,一个是user, 一个是post
: user:
: id account data_order
: 1 AAA 2
: 2 BBB 1
: 3 CCC 3
: post:
: id user_id content post_time(2018-XX-XX)
: 1 1 ... 2018-04-25
: 2 2 ... 2018-04-25
: 3 3 ... 2018-04-27
: 4 1 ... 2018-04-27
: 5 2 ... 2018-04-27
: 6 1 ... 2018-04-27
: 7 3 ... 2018-04-27
: 想要统计某一天(2018-04-27)使用者的留言数量,并依照user的data_order排序
: 希望结果如下
: account post_num
: BBB 1
: AAA 2
: CCC 2
: 有几个疑问
: 1.效能是写在一句sql语法比较好,还是先依据data_order排序后,再各别统计比较好?
: 2.如果是写在一句sql写法这样对吗?
: SELECT user.account, count(post.id) AS post_num
: FROM user, post
: WHERE user.id = post.user_id AND post.post_time = '2018-04-27'
: GROUP BY post.user_id
: ORDER BY user.data_order
: 3.用 LEFT JOIN 的话效能会比较好吗?还是其实都差不多?
: SELECT user.account, count(post.id) AS post_num
: FROM user
: LEFT JOIN user ON post.user_id = user.id
: WHERE post.post_time = '2018-04-27'
: ORDER BY user.data_order
: 先感谢各位大神了!!

Links booklink

Contact Us: admin [ a t ] ucptt.com