我正在查询基于user_id和特定日期和操作的多个表的结果,但我还有一个名为user_notes的单独表:
user_notes
| id | user_id | note | date |
------------------------------------------------------------------------
| 1 | 10 | First note. | 2016-01-01 |
| 2 | 10 | Second note. | 2016-01-02 |
| 3 | 11 | First note. | 2016-01-03 |
| 4 | 11 | Second note. | 2016-01-04 |
| 5 | 11 | Third note. | 2016-01-05 |
我想知道当我与其他表连接时,如何将所有这些注释及其日期作为单独的列返回到每个记录/结果中,并且每个user_id只返回一行,因为最终结果看起来如此像这样的东西:
final_result
| user_id | other_data | note1 | date1 | note2 | date2 | note3 | date3 |...
---------------------------------------------------------------------------------------------------------
| 10 | .......... | First note. | 2016-01-01 | Second note. | 2016-01-02 | | | ...
| 11 | .......... | First note. | 2016-01-03 | Second note. | 2016-01-04 | Third note. | 2016-01-05 | ...
依此类推......最多可以有10个音符,因此每个音符最多可以有10个额外的音符"音符"和"日期"条目。
任何想法如何实现,如果有的话?
答案 0 :(得分:0)
这可以通过这个技巧来实现:
select main.user_id,
first_note.note as note1, first_note.date,
second_note.note as note2, second_note.date,
...
from user_notes as main
inner join (select * from user_notes where user_id = main.user_id limit 0,1 ) as first_note on main.user_id = first_note.user_id
inner join (select * from user_notes where user_id = main.user_id limit 1,1 ) as second_note on main.user_id = second_note.user_id
...