使用mysql加入两个表并按日期排序

时间:2013-08-10 16:49:09

标签: mysql union

我已经考虑了许多这个问题的解决方案,但我仍然无法解决这个问题。

SELECT Year FROM (SELECT DISTINCT YEAR(detDate1) AS Year 
FROM growl_details WHERE publish = 'y' AND pubNews = 'y' 
UNION 
SELECT DISTINCT YEAR(detDate1) AS Year FROM growl_pl_details
WHERE publish = 'y' AND pubNews = 'y') AS t ORDER BY 'Year' ASC

我有两个表,growl_details和growl_pl_details,我试图让它们只显示信息存在的年份,然后用它来创建一个表格,其中包含与当年有关的数据页面的链接。

显然我希望这些年按顺序展示,但上面的代码似乎是单独订购它们并且它们彼此继续......

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您的查询(格式化,以便我可以阅读):

SELECT Year
FROM (SELECT DISTINCT YEAR(detDate1) AS Year
      FROM growl_details
      WHERE publish = 'y' AND pubNews = 'y'
      UNION
      SELECT DISTINCT YEAR(detDate1) AS Year
      FROM growl_pl_details
      WHERE publish = 'y' AND pubNews = 'y'
     ) AS t
ORDER BY 'Year' ASC;

问题是由order by子句引起的。尝试将单引号更改为引号:

ORDER BY `Year` ASC;

单引号用于字符串常量。返回引号围绕事物的名称。所以,你的原始查询是按常量排序 - 产生任意顺序。