假设我有3张桌子。 它们被称为用户,线程,帖子。我需要知道有多少帖子&线程 用户已在一个sql行中创建。做这个的最好方式是什么?加入我会做类似跟随的事情,这是正确/最好的方法吗?但我如何计算?
SELECT *,
FROM users
LEFT JOIN threads on threads.user_id=users.user_id
LEFT JOIN posts on posts.user_id=users.user_id
WHERE user_id='1'
答案 0 :(得分:3)
你可以使用类似这样的东西来应用和聚合函数来得到总数:
SELECT u.user_id,
coalesce(TotalThreads, 0) + coalesce(TotalPosts, 0) Total
FROM users u
LEFT JOIN
(
select user_id, count(thread_id) TotalThreads
from threads
group by user_id
) t
on t.user_id=u.user_id
LEFT JOIN
(
select user_id, count(post_id) TotalPosts
from posts
group by user_id
) p
on p.user_id=u.user_id
WHERE u.user_id='1'
如果您希望值分开,则:
SELECT u.user_id,
coalesce(TotalThreads, 0) TotalThreads,
coalesce(TotalPosts, 0) TotalPosts
FROM users u
LEFT JOIN
(
select user_id, count(thread_id) TotalThreads
from threads
group by user_id
) t
on t.user_id=u.user_id
LEFT JOIN
(
select user_id, count(post_id) TotalPosts
from posts
group by user_id
) p
on p.user_id=u.user_id
WHERE u.user_id='1'
答案 1 :(得分:0)
首先,你在SELECT *
后有逗号逗号。第二,当你想要线程和帖子时,为什么查询用户表?第三,为什么(是吗?)user_id
一个char
?
SELECT COUNT(user_id) FROM threads WHERE user_id='1'
SELECT COUNT(user_id) FROM posts WHERE user_id='1'
如果您想在一个查询中使用UNION
,请使用
答案 2 :(得分:0)
你基本上就在那里。由于count
是aggregate function,因此您只需按user_id
进行分组:
select users.user_id as [User ID]
,count(threads.user_id) as [Number of Threads]
,count(posts.user_id) as [Number of Posts]
from users
left join threads on threads.user_id = users.user_id
left join posts on posts.user_id = users.user_id
where user_id = '1'
group by users.user_id
这样,您的where
子句变为可选。如果您想要一个具有相应线程/帖子数的所有用户的明确列表,您可以将其删除。
答案 3 :(得分:-1)
SELECT
COUNT() as posts,
FROM users
LEFT JOIN threads on threads.user_id=users.user_id
LEFT JOIN posts on posts.user_id=users.user_id
WHERE user_id='1'
答案 4 :(得分:-1)
这会有用吗?
SELECT COUNT (*) FROM users u, thread t, posts p
WHERE t.user_id=u.user_id
AND p.user_id=u.user_id
AND user_id='1'
我不会热衷于SQL ......