我有两个表,每个表都有一个名为" date"的列。我想加入他们,但要对这个通常格式化的日期列进行排序。
例如,这是我的两个表:
Birthdays
+--------+---------+
| Date | Name |
+--------+---------+
| 03/10 | John |
+--------+---------+
| 09/24 | Sara |
+--------+---------+
Holidays
+--------+----------+
| Date | Title |
+--------+----------+
| 07/04 | July 4th |
+--------+----------+
| 12/25 | Xmas |
+--------+----------+
我想要做的是加入它们并按日期排序。常规的两列排序不会起作用,因为如果我没有指定哪个表的“日期”列,我正在寻找它会给我一个不明确的"模糊的"错误,如果我在它们之间指定一个共同点,它将对一个进行排序并对另一个进行排序。
以下是我想要使用该示例数据的输出:
+--------+---------+----------+
| Date | Name | Title |
+--------+---------+----------+
| 03/10 | John | |
+--------+---------+----------+
| 09/24 | Sara | |
+--------+---------+----------+
| 07/04 | | July 4th |
+--------+---------+----------+
| 12/25 | | Xmas |
+--------+---------+----------+
非常感谢任何关于如何做到这一点的建议,谢谢!
答案 0 :(得分:1)
SELECT u.Date, b.Name, h.Title
FROM
(SELECT Date FROM Birthdays UNION SELECT Date FROM Holidays) u
LEFT JOIN Birthdays b ON u.Date=b.Date
LEFT JOIN Holidays h ON u.Date=h.Date
或者您也可能想要对名称列进行分组,例如使用GROUP_CONCAT:
SELECT u.Date, GROUP_CONCAT(b.Name) Names, h.Title
FROM
(SELECT Date FROM Birthdays UNION SELECT Date FROM Holidays) u
LEFT JOIN Birthdays b ON u.Date=b.Date
LEFT JOIN Holidays h ON u.Date=h.Date
GROUP BY
u.Date, h.Title
假设多个名字可以共享同一个生日,并且一次只能有一个假期。
答案 1 :(得分:0)
试试这个。
select date, name, title from (
select Date, name, '' as Title
from Birthdays
union
select Date, '', title
from Holidays ) table
order by date
答案 2 :(得分:0)
使用UNION - 声明
SELECT * FROM (
SELECT `Date`, 'Birthday' AS `Type`, `Name` FROM `Birthday`
UNION
SELECT `Date`, 'Holiday' AS `Type`, `Title` FROM `Holiday`
) AS `AllSpecialDays` ORDER BY `Date`