1

我有几个这样的mysql表:

博客

  • entry_id
  • 成员_d

文章

  • entry_id
  • 成员_d

帖子

  • entry_id
  • 成员_d

我想计算特定成员的总条目。我目前有这个(虽然这个例子只使用了 3 个表,但实际上大约有 10 - 20 个表的结构都相同):

SELECT COUNT('member_id') FROM blogs WHERE member_id=3 LIMIT 1;
SELECT COUNT('member_id') FROM articles WHERE member_id=3 LIMIT 1;
SELECT COUNT('member_id') FROM posts WHERE member_id=3 LIMIT 1;

你看到重复了吗?有什么方法可以将其压缩为 1 个查询,例如(怀疑这是否有效):

SELECT COUNT(blogs.'member_id') as total_blogs, 
COUNT(articles.'member_id') as total_articles, 
COUNT(posts.'member_id') as total_posts  
FROM blogs,articles,posts WHERE member_id=3 LIMIT 1;

PS 尝试搜索 stackoverflow 和 google,但不断获取有关使用 COUNT(*) 或使用组等的信息...

4

3 回答 3

1

这个作品,

SELECT  
(SELECT COUNT('member_id') FROM blogs WHERE member_id=3) as total_blogs,
(SELECT COUNT('member_id') FROM articles WHERE member_id=3) as total_articles,
(SELECT COUNT('member_id') FROM posts WHERE member_id=3) as total_posts

并在一条记录中为您提供所有信息

于 2012-11-22T19:09:33.527 回答
0
SELECT COUNT(*) FROM(
    SELECT member_id FROM blogs
    UNION ALL
    SELECT member_id FROM articles
    UNION ALL
    SELECT member_id FROM posts
) AS activity
WHERE member_id=3
GROUP BY member_id

Sqlfiddle 演示:http ://sqlfiddle.com/#!2/366bd/2

于 2012-11-22T19:10:06.990 回答
0

只是为了记录,我在这里添加第二个解决方案,它允许在单个查询中选择多个 ID

SELECT m.member_id, 
       COALESCE(blogs.total_blogs,0)       as total_blogs, 
       COALESCE(articles.total_articles,0) as total_articles, 
       COALESCE(posts.total_posts,0)       as total_posts
FROM   members  m     -- I guess this table exists 
LEFT JOIN (SELECT member_id, COUNT('member_id') as total_blogs    FROM blogs    GROUP BY member_id) as blogs     on m.member_id = blogs.member_id
LEFT JOIN (SELECT member_id, COUNT('member_id') as total_articles FROM articles GROUP BY member_id) as articles  on m.member_id = articles.member_id
LEFT JOIN (SELECT member_id, COUNT('member_id') as total_posts    FROM posts    GROUP BY member_id) as posts     on m.member_id = posts.member_id
where m.member_id in (3,4,5)

在这里摆弄

于 2012-11-22T21:18:05.577 回答