重建MySql查询

时间:2016-01-25 15:35:01

标签: mysql sql

我有一个包含两列的'用户'表:'id'和'username'。现在该表中有两行'Bill'和'Mike'。我需要查看此表包含的内容 3位用户:'Bill','Mike'和'Sarah'。

查询

select username from users where username in ('Bill', 'Mike', 'Sarah');

返回结果

         username |
-------------------
  Bill            | 
-------------------
  Mike            |
-------------------

但我需要这样的结果

     username     | has |
-------------------------
  Bill            |  1  |
-------------------------
  Mike            |  1  |
-------------------------
  Sarah           |  0  |
-------------------------

我的数据库是MySql。我该如何重建我的查询?

我想要总共3行。如果添加'Sarah',则结果必须为:

     username     | has |
-------------------------
  Bill            |  1  |
-------------------------
  Mike            |  1  |
-------------------------
  Sarah           |  1  |
-------------------------

如果table为空,则结果必须为:

     username     | has |
-------------------------
  Bill            |  0  |
-------------------------
  Mike            |  0  |
-------------------------
  Sarah           |  0  |
-------------------------

3 个答案:

答案 0 :(得分:0)

你可以尝试这个://可能会出现拼写错误

select username, Count(username) as has from users 
where username in ('Bill', 'Mike', 'Sarah')
UNION
select username, 0 as has from
(select username, 1 as has from ('Bill')
UNION ALL
select username, 1 as has from ('Mike')
UNION ALL
select username, 1 as has from ('Sarah'))

答案 1 :(得分:0)

一种方法:

select c.username, count(u.username) as has 
from (select 'Bill' as username union select 'Mike' union select 'Sarah') as c
join users as u on c.username = u.username
group by c.username

答案 2 :(得分:0)

SELECT AllUsers.UserName,  CASE WHEN U2.UserName IS NULL THEN 0 ELSE 1 END as Has
FROM
(SELECT UserName 
FROM [User] U 
WHERE U.UserName in ('Bill', 'Mike', 'Sarah')
UNION
SELECT 'Bill'
UNION 
SELECT 'Mike'
UNION
SELECT 'Sarah') AllUsers
LEFT OUTER JOIN [User] U2 ON U2.UserName = AllUsers.UserName