mysql select data from two tables and different st

2019-07-09 04:18发布

问题:

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.