2017-08-03 65 views
3

我有一個聯接查詢返回的結果:如何在此連接查詢中省略重複結果?

我教課:

2017-04-02 : 10:00:00 - 12:00:00 
2017-04-02 : 15:00:00 - 16:30:00 
2017-04-02 : 17:00:00 - 18:00:00 
2017-04-02 : 18:10:00 - 19:10:00 
2017-04-03 : 10:00:00 - 12:00:00 
2017-04-04 : 10:00:00 - 12:00:00 
2017-04-05 : 17:45:00 - 18:45:00 
2017-04-08 : 08:50:00 - 10:20:00 
2017-04-08 : 10:30:00 - 12:00:00 
2017-04-08 : 17:30:00 - 18:30:00 
... 

是否可以顯示每個日期只有一次使用MySQL服務器5.7 SQL?或者應該這樣做以後使用PHP?結果是這樣的,因爲可以在一天內教授多個課程,但只有一天只能有一堂課。

像這樣:我教課:

2017-04-02 : 10:00:00 - 12:00:00 
      15:00:00 - 16:30:00 
      17:00:00 - 18:00:00 
      18:10:00 - 19:10:00 
2017-04-03 : 10:00:00 - 12:00:00 
2017-04-04 : 10:00:00 - 12:00:00 
2017-04-05 : 17:45:00 - 18:45:00 
2017-04-08 : 08:50:00 - 10:20:00 
      10:30:00 - 12:00:00 
      17:30:00 - 18:30:00 
... 

這裏的查詢。我試着爲日期連接做一個子查詢,但我無法讓它工作。

SELECT 
    lessons_date, 
    start_times, 
    end_times 
FROM lessons 
JOIN lesson_date 
    ON id_lessons_date = lesson_date_id_lessons_date 
JOIN start_time 
    ON id_start_times = start_time_has_end_time_start_time_id_start_times 
JOIN end_time 
    ON id_end_times = start_time_has_end_time_end_time_id_end_times; 
+0

編輯你的問題,並顯示你想要的結果。並用您正在使用的數據庫標記您的問題。 –

回答

1

數據庫未用於顯示數據,因爲您想要將它們呈現在網頁中,因此您必須找到一種方法從數據庫中提取它們,然後根據提取方式顯示它們。

SELECT 
    lessons_date, 
    group_concat(start_times SEPARATOR ',') start_times, 
    group_concat(end_times SEPARATOR ',') end_times 
FROM lessons 
JOIN lesson_date 
    ON id_lessons_date = lesson_date_id_lessons_date 
JOIN start_time 
    ON id_start_times = start_time_has_end_time_start_time_id_start_times 
JOIN end_time 
    ON id_end_times = start_time_has_end_time_end_time_id_end_times; 
GROUP BY lessons_date 

然後在你PHP添加喜歡的東西:

$start_times = explode(",", $row["start_times"]); // array of times 
for ($time as $start_times) { 
    echo $time; 
} 
1

這不是你要找的,可能有一個更優雅的方式來做到這一點,但這裏正是對你的想法:

SELECT 
    CreatedOn = 
     CASE 
     WHEN name is null 
     THEN CreatedOn 
     ELSE null 
     END 
    , Name 
    FROM (
     select distinct 
      createdon 
      ,null as name 
      ,createdon as c2 
     FROM account 
     UNION 
     SELECT 
      a.createdon 
      ,a.name 
      ,a.createdon as c2 
      FROM account a 
      JOIN account b on a.createdon = b.createdon 
     ) x 
    ORDER BY c2, name 

返回此:

SQL results

你可能要考慮用PHP格式化它...

+0

我寧願在服務器或客戶端執行它,因爲它與數據表示相關而不是提取。 – pso

0

,您可以嘗試。這將給出確切的結果。

SELECT 
    temp.lessons_date , 
    GROUP_CONCAT(start_times SEPARATOR '<br/>') , 
    GROUP_CONCAT(end_times SEPARATOR '<br/>') FROM (
     SELECT 
     lessons_date, 
     start_times, 
     end_times 
    FROM lessons 
    JOIN lesson_date 
     ON id_lessons_date = lesson_date_id_lessons_date 
    JOIN start_time 
     ON id_start_times = start_time_has_end_time_start_time_id_start_times 
    JOIN end_time 
     ON id_end_times = start_time_has_end_time_end_time_id_end_times ORDER BY temp.lessons_date 


    ) temp GROUP BY temp.lessons_date