简体   繁体   中英

MySQL Multiple Table Query and Results

I am trying to query multiple tables and trying to display the results as follows...

Tables...

news
id    title      news_datestamp
1      news 1       01/01/2001
2      news 2       01/05/2001

articles    title          articles_datstamp
1            article 1         01/04/2001
2            article 2         01/06/2001

I'm trying to get a single script to display the results as...

News 1 01/01/2001
Article 1 01/04/2001
News 2 01/05/2001
Article 2 01/06/2001

Any ideas?

It looks to me like you want a union of the news and article tables.

SELECT * FROM
  ( SELECT title,
           news_datestamp AS datestamp
      FROM news
     UNION ALL
    SELECT title,
           article_datestamp AS datestamp
     FROM articles
    ) AS everything
   ORDER BY datestamp, title

You could simple use a Union to merge results in a subselect and sort the final table:

SELECT * FROM (
  SELECT id, title, news_datestamp AS datestamp, "news" AS type FROM news
  UNION ALL
  SELECT articles AS id, title, article_datestamp AS datestamp, "article" AS type FROM articles
) AS temptable
ORDER BY datestamp

The type column will help you to identify id references later.

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