从SQL中SOME status = 0的表中选择所有信息

时间:2015-04-24 08:04:32

标签: mysql sql

我在MySQL数据库中有以下表格

account | status
1       |   1
1       |   0
1       |   0
2       |   0
2       |   0
2       |   0
3       |   1
3       |   1
3       |   1

如何从此表中选择帐户的某些状态等于零的所有信息?在此示例中,结果应为

account | status
1       |   1
1       |   0
1       |   0
2       |   0
2       |   0
2       |   0

因为对于account.name = 3,所有状态均为1.

谢谢, 弗拉基米尔

4 个答案:

答案 0 :(得分:3)

尝试这种方式:

select account, status
from tab
where account in (select account 
                  from tab 
                  where status = 0)

Sql fiddle demo

答案 1 :(得分:1)

SELECT * FROM Table1 WHERE `account` IN 
(SELECT `account` FROM Table1 WHERE `status` = 0)

FIDDLE

答案 2 :(得分:0)

JOIN版本:

select t1.*
from tablename t1
  join (select distinct account
        from tablename
        where status = 0) t2
  ON t1.account = t2.account

(ANSI SQL语法,但我认为它也适用于MySQL。)

答案 3 :(得分:0)

编写一个子查询,查找status = 0的所有帐户,并将其与表格连接。

SELECT t1.*
FROM YourTable AS t1
JOIN (SELECT DISTINCT account
      FROM YourTable
      WHERE status = 0) AS t2
ON t1.account = t2.account

在MySQL中,这可能比其他答案中的IN查询表现更好。 MySQL并没有很好地优化它们。