简体   繁体   中英

mysql select data from two tables and different structure

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM