MySQL多表查询和结果

时间:2013-09-20 19:09:52

标签: php mysql

我正在尝试查询多个表并尝试按如下方式显示结果...

表...

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

我正在尝试使用单个脚本将结果显示为...

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

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在我看来,你想要一个newsarticle表的联合。

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

答案 1 :(得分:1)

您可以简单地使用Union合并子选择中的结果并对最终表进行排序:

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

type列将帮助您稍后识别ID引用。