【问题标题】:MySQL SELECT with join, count, order byMySQL SELECT 与 join、count、order by
【发布时间】:2014-04-03 11:14:18
【问题描述】:

我正在尝试按如下方式加入两个表:

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、tours_schedules.tour_id 与 tours.tour_id 匹配的 tours_schedules 中的记录计数以及最早匹配 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

【问题讨论】:

    标签: sql select join count


    【解决方案1】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多