我有几个像这样的mysql表:
博客
制品
帖子
我想计算特定成员的总条目数。我目前有这个(虽然这个例子只使用了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;
P.S。尝试搜索stackoverflow和谷歌,但继续得到有关使用COUNT(*)或使用组等的事情......
答案 0 :(得分: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
并仅在一条记录中提供所有信息
答案 1 :(得分: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
答案 2 :(得分: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)
小提琴here