简体   繁体   中英

MySQL select based on precedence of a column's values

Say you have a dynamic view of a table that consists of the following entries

| id | type |
| 1  | cat  |
| 2  | dog  |
| 3  | bunny|

The catch with this is that sometimes there may not be an id with a type of "cat" it could potentially look like

| id | type |
| 1  | dog  |
| 2  | bunny|

How would one write a query for this table to select a single row based on precedence of type .

For example, if the ranking of type was cat > dog > bunny , I would want the first entry from that table with the highest ranking condition.

If we call our view pets , which has ORDER BY id ASC then we would have a query that looks something like this

SELECT *
FROM pets
WHERE type = 'cat' > 'dog' > 'bunny' -- here is where I need help
LIMIT 1

I've tried things like

IF EXISTS (SELECT * 
       FROM   pets 
       WHERE  type = "cat") 

THEN SELECT * FROM pets WHERE condition = "cat" LIMIT 1
-- etc... down the ranking 

Can't seem to get this to work though. Help is much appreciated.

In MySQL, I would use field() :

SELECT *
FROM pets
WHERE type IN ('cat', 'dog', 'bunny')
ORDER BY field(type, 'cat', 'dog', 'bunny')
LIMIT 1

If you don't want to deal with the WHERE clause, you can do:

SELECT *
FROM pets
ORDER BY field(type, 'bunny', 'dog', 'cat') DESC
LIMIT 1

You need to go backwards because non-matches are returned as 0 .

You can try to use CASE WHEN make the order number in ORDER BY , do your customer order by then LIMIT 1

CREATE TABLE pets(
  ID INT,
  type VARCHAR(50)
);


INSERT INTO pets VALUES ( 1  , 'cat');
INSERT INTO pets VALUES ( 2  , 'dog');
INSERT INTO pets VALUES ( 3  , 'bunny');
INSERT INTO pets VALUES ( 4 , 'TST');

Query 1 :

SELECT *
FROM pets
ORDER BY CASE 
    WHEN type = 'cat' THEN 1  
    WHEN type = 'dog' THEN 2 
    WHEN type = 'bunny' THEN 3 
    ELSE 4  
    END 
LIMIT 1

Results :

| ID | type |
|----|------|
|  1 |  cat |

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