0

I have two tables which each have a column named "date". I'd like to JOIN them but sort on that commonly formatted date column.

For example, here are my two tables:

Birthdays
+--------+---------+
| Date   | Name    |
+--------+---------+
| 03/10  | John    |
+--------+---------+
| 09/24  | Sara    |
+--------+---------+

Holidays
+--------+----------+
| Date   | Title    |
+--------+----------+
| 07/04  | July 4th |
+--------+----------+
| 12/25  | Xmas     |
+--------+----------+

What I want to do is to JOIN them and ORDER BY the dates. The regular two-column sort wont work because if I don't specify which table's Date column I'm looking for it gives me an "ambiguous" error, and if I specify both with a common between them it will sort one and subsort the other.

Here is the output I want using that example data:

+--------+---------+----------+
| Date   | Name    | Title    |
+--------+---------+----------+
| 03/10  | John    |          |
+--------+---------+----------+
| 09/24  | Sara    |          |
+--------+---------+----------+
| 07/04  |         | July 4th |
+--------+---------+----------+
| 12/25  |         | Xmas     |
+--------+---------+----------+

Any advice on how to do this would be much appreciated, thanks!

4

3 回答 3

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

or maybe you also want to group the name column, using for example 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

assuming that multiple names can share the same birthday, and that there could be only a holiday at a time.

于 2013-11-14T20:32:29.960 回答
0

Try this.

select date, name, title from (
select Date, name, '' as Title
  from Birthdays
 union 
select Date, '', title
  from Holidays ) table 
 order by date
于 2013-11-14T19:48:02.167 回答
0

Use a UNION-statement

SELECT * FROM (
    SELECT `Date`, 'Birthday' AS `Type`, `Name` FROM `Birthday`
    UNION
    SELECT `Date`, 'Holiday' AS `Type`, `Title` FROM `Holiday`
) AS `AllSpecialDays` ORDER BY `Date`
于 2013-11-14T19:49:18.170 回答