选择bool,表示行的ID是否在另一个表中

时间:2014-05-02 01:17:46

标签: mysql

有没有办法使用IN语句在结果集中获取bool列?

我知道我可以做这样的事情,只选择在另一个表中找到ID的所有行,然后选择反之以选择那些没有的行,从那里得到真/假:

SELECT * FROM people WHERE id IN (SELECT staff.personID FROM staff)

但我希望能有类似的东西:

SELECT
    people.*,
    (people.id IN (SELECT staff.personID FROM staff)) AS marked
FROM people

结果:

+----+--------+--------+
| id | name   | marked |
+----+--------+--------+
| 1  | Marty  | 1      |
| 2  | Steven | 1      |
| 3  | Daniel | 0      | <--- Not found in 'staff'.
| 4  | James  | 1      |
+----+--------+--------+

1 个答案:

答案 0 :(得分:1)

您的查询应该有效:

SELECT people.*,
       (people.id IN (SELECT staff.personID FROM staff)) AS marked
FROM people;

我认为它会更有效率:

SELECT p.*,
       (exists (SELECT 1 FROM staff s WHERE s.PersonID = p.id)) AS marked
FROM people p;