MySQL get rows but prefer one column value over another

前端 未结 4 679
忘掉有多难
忘掉有多难 2021-01-24 12:33

A bit of a strange one, I want to write a MySQL query that will get results from a table, but prefer one value of a column over another, ie

id   name    value            


        
4条回答
  •  执念已碎
    2021-01-24 13:11

    If I understand correctly, you want the value of a name given a specific priority, or the value associated with a NULL priority. (You do not necessarily want the MAX(priority) that exists.)

    Yes, you've got some awkward design issues which you should address, but let's solve the problem you do have at present (and you can later migrate to the problem you ought to have :) ):

    mysql> SET @priority = 1;  -- the priority we want, if recorded
    
    mysql> PREPARE stmt FROM "
           SELECT
             t0.*
           FROM
             t t0
           LEFT JOIN
             (SELECT DISTINCT name, priority FROM t WHERE priority = ?) t1
               ON t0.name = t1.name
           WHERE
             t0.priority = t1.priority
               OR
             t1.priority IS NULL
           ";
    
    mysql> EXECUTE stmt USING @priority;
    +----+-------+--------+----------+
    | id | name  | value  | priority |
    +----+-------+--------+----------+
    |  2 | name1 | valueX |        1 | 
    |  3 | name2 | value2 |     NULL | 
    |  4 | name3 | value3 |     NULL | 
    +----+-------+--------+----------+
    3 rows in set (0.00 sec)
    

    (Note that I changed the prioritized value of "name1" to "valueX" in the above -- your original formulation had identical value values for "name1" regardless of priority, which made it hard for me to understand why you cared to discriminate one from the other.)

提交回复
热议问题