我正在尝试按如下方式加入两个表:
tours tours_schedules
--------------------- ---------------------------------
tour_id | title | schedule_id | tour_id | startdate
--------------------- ---------------------------------
1 | Day Trip 1 1 | 1 | 2014-05-23
2 | Day Trip 2 2 | 1 | 2014-05-24
3 | 2 | 2014-06-01
4 | 1 | 2014-05-17
我想选择能告诉我tours.tour_id,tours.title的结果,tour_schedules中的tours记录,其中tours_schedules.tour_id与tours.tour_id匹配,以及最早匹配的tours_schedules.startdate的日期。
结果应如下所示
results
---------------------------------------------------------------
tour_id | title | schedule_count | earliest_startdate
---------------------------------------------------------------
1 | Day Trip 1 | 3 | 2014-05-17
2 | Day Trip 2 | 1 | 2014-06-01
我做不到,有人能把我从痛苦中解救出来吗?!以下是我尝试过的众多内容。计算tour_schedules似乎会在选择的游览中停止多行。
SELECT DISTINCT t.title, a.startdate, COUNT (DISTINCT a.startdate) AS schedule_count
FROM tours t
INNER JOIN tours_schedules a
ON t.tour_id = a.tour_id
WHERE t.category_id = 1
ORDER BY a.startdate ASC
SELECT DISTINCT t.title
FROM tours t
RIGHT JOIN tours_schedules a
ON t.tour_id = a.tour_id
ORDER BY a.startdate
SELECT a.schedule_id, COUNT(a.schedule_id) AS schedule_count, t.title
FROM tours_schedules a
JOIN tours t
ON a.tour_id = t.tour_id
ORDER BY a.startdate
SELECT title, tour_id FROM tours
UNION ALL
SELECT startdate FROM tours_schedules
SELECT t.title, t.tour_id, (SELECT a.startdate)
FROM tours t
JOIN tours_schedules a
WHERE t.tour_id = a.tour_id
SELECT t.title, t.tour_id, (SELECT a.startdate LIMIT 1), (SELECT COUNT(a.startdate) WHERE t.tour_id = a.tour_id)
FROM tours t
JOIN tours_schedules a
WHERE t.tour_id = a.tour_id
答案 0 :(得分:2)
SELECT a.schedule_id,
COUNT(a.schedule_id) AS schedule_count,
MIN(a.startdate) AS earliest_startdate ,
t.title
FROM tours_schedules a
JOIN tours t
ON a.tour_id = t.tour_id
GROUP BY t.tour_id