条件MySQL查询

时间:2011-04-02 10:36:06

标签: php mysql

我有一个包含列的表:conditional1,conditional2,data。如果其中任何行也包含conditional2 = value2,我需要返回conditional1 = value1的所有行。我怎么能这样做?

编辑:对于我所要求的内容存在一些困惑。

如果您有专栏

`conditional1 | conditional2 |数据

A | A |甲

A | B | A`

如果conditional1 = A和conditional2 = B

,我想返回两行

编辑2:仍有一些混乱。

这是另一个例子:

conditional1 | conditional2 |数据

1 | 1 |甲

1 | 2 |乙

2 | 1 | ç

2 | 2 | d

如果conditional1 = 1且conditional2 = 1,则应返回

1 | 1 |甲

1 | 2 |乙

如果conditional1 = 2且conditional2 = 1,则应返回

2 | 1 | ç

2 | 2 | d

如果conditional1 = 2且conditional2 = 2,则应返回

2 | 1 | ç

2 | 2 | d

如果conditional1 = 2且conditional2 = 3,则不应返回任何行。

2 个答案:

答案 0 :(得分:3)

select *
from tbl A
where conditional1 = 'A'
and exists (
  select * from tbl B
  where B.conditional1 = 'A' and B.conditional2 = 'B')

或更友好的MySQL版本

select * from tbl
where conditional1 in
(
    select conditional1 
    from tbl
    where conditional1 = 'A' and conditional2 = 'B'
)

答案 1 :(得分:0)

SELECT * FROM table 
    WHERE conditional1 = 'A' AND 1 IN 
        ( SELECT 1 FROM table WHERE conditional1 = 'A' AND conditional2 = 'B' LIMIT 1 )

我想我终于明白了!