1

假设我有 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'
4

5 回答 5

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'
于 2013-01-11T10:19:21.297 回答
0

首先,您在 . 之后有杂散逗号SELECT *。第二,当你想要线程和帖子时,为什么要查询用户表?第三,为什么(是?)user_ida char

SELECT COUNT(user_id) FROM threads WHERE user_id='1'
SELECT COUNT(user_id) FROM posts WHERE user_id='1'

UNION如果您想在一个查询中使用它。

于 2013-01-11T10:18:17.240 回答
0

你基本上在那里。因为count是一个聚合函数,您可以简单地按以下方式分组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子句就变成了可选的。如果您想要所有用户的不同列表及其相应的线程/帖子计数,则可以将其删除。

于 2013-01-11T10:22:29.897 回答
-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'
于 2013-01-11T10:18:26.753 回答
-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 不是很感兴趣……

于 2013-01-11T10:19:38.167 回答