开发者

Conditional MySQL Query

I have a table with columns: conditional1, conditional2, data. I need to return all the rows where conditional1 = value1 if any of those rows also contains conditional2 = value2. How can I do this?

Edit: There's some confusion about what I'm asking.

If you have columns

`conditional1 | conditional2 | data

A | A | A

A | B | A`

I want to return both rows if conditional1 = A and conditional2 = B

Edit 2: There's still some confusion.

Here is another example:

conditional1 | conditional2 | data

1 | 1 | A

1 | 2 | B

2 | 1 | C

2 | 2 | D

If conditional1 = 1 and conditional2 = 1, it should return

1 | 1 | A

1 | 2 | B

If conditional1 = 2 and conditional2 = 1, it should return

2 | 1 | C

2 | 2 | D

If conditional1 = 2 and conditional2 = 2, it should return

2 | 1 | C

2 | 2 | D

If conditional1 = 2 and conditional2 = 3, it should return no rows.开发者_开发问答


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

or a more MySQL friendly version

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


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

I think I finally understand!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜