MySQL table order by one column when other column has a particular value

感情迁移 提交于 2019-12-12 04:08:17

问题


I have two mysql tables record_items,property_values with the following structure.

table : property_values (column REC is foreign key to record_items)

id(PK)|REC(FK)| property | value|
 1    | 1     | name     |   A  |
 2    | 1     | age      |   10 |
 3    | 2     | name     |   B  |
 4    | 3     | name     |   C  |
 5    | 3     | age      |   9  |

table: record_items

id(PK) |col1|col2 |col3| 
1      | v11| v12 | v13|
2      | v21| v22 | v23|
3      | v31| v32 | v33|
4      | v41| v42 | v43|
5      | v51| v52 | v53|

record_items table contains only basic information about the record, where as property_values table keeps record_item as a foreign key and each property and its value is saved in a separate row.

Now I want to get the record_items sorted based on a particular property, say by age. My HQL query will be like

Select distinct rec from PropertyValues where property="age" order by value;

But this query will be skipping record 2 since it don't have an entry for property age. I expect the result to have the records which contains age property in sort order appended by those which don't have age property at all. How can I query that?


回答1:


Here is a raw MySQL query which should do the trick:

SELECT t1.*
FROM record_items t1
LEFT JOIN property_values t2
    ON t1.id = t2.REC AND
       t2.property = 'age'
ORDER BY CASE WHEN t2.value IS NULL THEN 1 ELSE 0 END, t2.Value

I notice that your Value column in property_values is mixing numeric and text data. This won't work well for sorting purposes.

Demo here



来源:https://stackoverflow.com/questions/43862509/mysql-table-order-by-one-column-when-other-column-has-a-particular-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!