我在'email'表上尝试了以下查询
SELECT email_id,count(*) as count FROM email
where email_id in ('a@a.com','b@b.com','c@c.com') group by email_id
结果
email_id count
a@a.com 3
c@c.com 2
但我想要像下面的序列一样的结果
email_id count
a@a.com 3
b@b.com 0
c@c.com 2
供您参考b@b.com不存在于电子邮件表中
架构
create table users
( userId int auto_increment primary key,
userName varchar(100) not null,
emailAddr varchar(200) not null
);
create table emails
( id int auto_increment primary key,
userId int not null
-- etc
);
insert users(userName,emailAddr) values ('Sally','sally10@gmail.com'),('Henry','h@h.com'),('JT','abcde@xxx.org');
insert emails(userId) values (1),(1),(1),(3),(3);
查询
select u.userId,u.emailAddr,count(e.id) as theCount
from users u
left join emails e
on e.userId=u.userId
group by u.userId,u.emailAddr
+--------+-------------------+----------+
| userId | emailAddr | theCount |
+--------+-------------------+----------+
| 1 | sally10@gmail.com | 3 |
| 2 | h@h.com | 0 |
| 3 | abcde@xxx.org | 2 |
+--------+-------------------+----------+
可以说,Left join
会收集缺失的电子邮件。
您可以使用:
SELECT e1.email_id, COUNT(e2.email_id) AS count
FROM (SELECT 'a@a.com' AS email_id
UNION
SELECT 'b@b.com'
UNION
SELECT 'c@c.com'
) AS e1
LEFT JOIN email AS e2 ON e1.email_id = e2.email_id
GROUP BY e1.email_id
此处演示
可能是这样的:
SELECT t.email_id,count(e.email_id) as count
FROM
(
select 'a@a.com' as email_id union all
select 'b@b.com' union all
select 'c@c.com'
) t
left join email e on t.email_id = e.email_id
group by t.email_id
试试这个:
SELECT 'a@a.com' as email_id,count(1) as `count` FROM email where email_id='a@a.com'
union
SELECT 'b@b.com' as email_id,count(1) as `count` FROM email where email_id='b@b.com'
union
SELECT 'c@c.com' as email_id,count(1) as `count` FROM email where email_id='c@c.com'