MySQL 如果 id 存在于另一个表中,则选择列为真/假
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25284986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
select column as true / false if id is exists in another table
提问by BeBest
I have 2 tables, one for members and another one for their services. Those are InnoDB tables on MySQL 5.6 server.
我有两张桌子,一张给会员,另一张给他们的服务。这些是 MySQL 5.6 服务器上的 InnoDB 表。
Members table:
成员表:
id | name | phone
----------------------------------------
1 Daniel 123456789
2 Liam 123456789
3 Lucas 123456789
Services table:
服务表:
MID | profile | lastSeen
----------------------------------------
1 2 2014-08-13 14:23:23
3 1 2014-08-12 15:29:11
I try to achieve this result:
我试图达到这个结果:
id | name | services
---------------------------------
1 Daniel true
2 Liam false
3 Lucas true
So if the user ID is exists in services table, the column services will be true or false otherwise.
因此,如果服务表中存在用户 ID,则服务列将是 true 或 false,否则。
I tried to do it with JOINs and Sub-Queries without success, so I need your help ;)
我试图用 JOIN 和子查询来做但没有成功,所以我需要你的帮助;)
回答by Girish
use LEFT JOIN
Services table, Try this query
使用LEFT JOIN
服务表,试试这个查询
SELECT members.id, members.name,
IF(services.mid IS NULL, FALSE, TRUE) as services
FROM members
LEFT JOIN services ON (members.id = services.mid)
回答by Lennart
select m.id, m.name, case when s.mid is null then false else true end
from members m
left join services s
on s.profile = m.id
回答by Muhammad Raheel
You can use a simple query like this
您可以使用这样的简单查询
SELECT
m.id,
m.name
IF(s.MID,true,false) services
FROM members m
LEFT JOIN services s ON s.profile = m.id