2017-08-03 63 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