Select separate rows from two tables, order by date

后端 未结 2 1444
情书的邮戳
情书的邮戳 2021-02-02 13:09

I don\'t want to any kind of JOIN here. I\'m building an RSS feed of two tables using PHP, and I want to select all the rows from the two tables, keeping t

相关标签:
2条回答
  • 2021-02-02 13:30

    Expanding on @Brendan Bullen's suggestion, here's an example using UNION ALL that should work for you:

    SELECT id as id, NULL as title, NULL as body, downloads as downloads, 
      views as views, created as created, 'foo' as table_name
    FROM foo
    UNION ALL
    SELECT NULL as id, title as title, body as body, NULL as downloads, 
      NULL as views, created as created, 'bar' as table_name
    FROM bar
    ORDER BY created ASC
    
    0 讨论(0)
  • 2021-02-02 13:47

    Using dummy columns to account for the different structures, a union to join them and a parent select to handle the ordering:

    SELECT * FROM (
        (SELECT foo.id, NULL AS title, NULL AS body, foo.downloads, foo.views, foo.created FROM foo)
        UNION ALL
        (SELECT NULL AS id, bar.title, bar.body, NULL AS downloads, NULL AS views, bar.created FROM bar)
    ) results
    ORDER BY created ASC
    
    0 讨论(0)
提交回复
热议问题