开发者

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: D开发者_如何学CATETIME.

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

Please help me out! =) thanks luca


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜