简体   繁体   中英

mysql SELECT column value dependent on another column

I have a table like this:

ID | Type   | woof | meow
1  |  dog   |  1   |  0
2  |  cat   |  1   |  1
3  |  dog   |  0   |  0
4  |  cat   |  0   |  1

I want to SELECT DISTINCT id, type WHERE if type=dog then woof=1, and if type=cat then meow=1. So my expect output would consist of row 1,2 and 4.

How can I do this? I am assuming with some sort of fancy IF or CASE statement but I couldn't easily figure it out from mysql's documentation.

Thanks

You can use AND and OR:

SELECT DISTINCT id, type 
FROM yourtable
WHERE (type='dog' AND woof=1) OR (type='cat' AND meow=1)

Note also that if your id field is unique (and I'm guessing that it is) then the DISTINCT is unnecessary here.

Just use simple boolean algebra:

SELECT DISTINCT id, type
FROM table
WHERE
  (type = 'dog' AND woof = 1) OR
  (type = 'cat' AND meow = 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM