MySQL get rows but prefer one column value over another

前端 未结 4 723
忘掉有多难
忘掉有多难 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:26

    This should do it:

    SELECT
         T1.id,
         T1.name,
         T1.value,
         T1.priority
    FROM
         My_Table T1
    LEFT OUTER JOIN My_Table T2 ON
         T2.name = T1.name AND
         T2.priority > COALESCE(T1.priority, -1)
    WHERE
         T2.id IS NULL
    

    This also allows you to have multiple priority levels with the highest being the one that you want to return (if you had a 1 and 2, the 2 would be returned).

    I will also say though that it does seem like there are some design problems in the DB. My approach would have been:

    My_Table (id, name) My_Values (id, priority, value) with an FK on id to id. PKs on id in My_Table and id, priority in My_Values. Of course, I'd use appropriate table names too.

提交回复
热议问题