Ordering query result by field from a different table (MySQL)

后端 未结 2 470
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 08:28

I have a MySQL table structure and need to get a specific query working but I just can\'t wrap my head around it somehow. First off, here\'s the relevant table structure.

<
相关标签:
2条回答
  • 2021-01-27 08:48

    If I understand correctly, you would use join:

    select f.*
    from folders f join
         werte w
         on w.folder_id = f.id
    where w.number = 2 
    order by f.approved, str_to_date(werte, '%d.%m.%Y');
    

    As a note: if you are doing to store dates in strings, then use the ISO standard format YYYY-MM-DD. If you used this format, the str_to_date() would be unnecessary, because an alphabetic ordering of the string representation would be correct.

    Also, if there might not be a match in the werte table, then you should use left join instead of inner join. The above assumes there is a match (or you only want rows that have a date).

    0 讨论(0)
  • 2021-01-27 08:59

    If you would like to avoid duplicates, you can use group by on the date:

    SELECT f.id, STR_TO_DATE(w.werte, '%d.%m.%Y') as d 
     FROM folders f JOIN werte w
     ON w.folder_id = f.id
     GROUP BY d
     ORDER BY d;
    
    0 讨论(0)
提交回复
热议问题