mysql select data from two tables and different structure

寵の児 提交于 2019-12-11 02:21:47

问题


Hi there i'm building up a kind of agenda/website with php/mysql. This agenda has public events and users' personal notes ordered by date. I need to load all the events from EVENTS TABLE in database and the notes from NOTES TABLE. But those two tables have a completely different structure and they just have one same field: DATETIME.

How can i sort by date public events and personal notes then?

Please help me out! =) thanks luca


回答1:


Improving Don's answer per OP comments, you can add a column to know what table the row was in.

SELECT  'events' As Tbl,
        datetime,
        location,
        organizer,
        NULL as notes
FROM    events
UNION
ALL
SELECT  'user_notes' As Tbl,
        datetime,
        NULL,
        NULL,
        notes
FROM    user_notes
ORDER
BY      datetime DESC



回答2:


Use a UNION ALL with two queries. Each table's query will just have NULL in all the columns for the other table. For example:

SELECT  'event' as type,
        datetime,
        location,
        organizer,
        NULL as notes
FROM    events
UNION
ALL
SELECT  'user_note',
        datetime,
        NULL,
        NULL,
        notes
FROM    user_notes
ORDER
BY      datetime DESC

The type field can either be a string or an integer to easily distinguish which table the row came from.



来源:https://stackoverflow.com/questions/5032995/mysql-select-data-from-two-tables-and-different-structure

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