将count(distinct)与复杂的选择条件mysql

时间:2018-07-06 20:04:15

标签: mysql select count

我想结合两个有效的mysql select语句:

SELECT 
    t2.*, 
    t1.Lang, 
    Filmname, 
    ColFI 
FROM Timetable t2, Contenttable t1 
WHERE DATE_ADD(STR_TO_DATE(CONCAT('201825',' Thursday'), '%x%v %W'), INTERVAL 0 DAY) = DateSZ 
    AND RoomSZ =1 AND t2.idFI = t1.id 
    AND deleteSZ = false 
ORDER BY TimeSZ

给我(当然还有一些其他不相关的栏目)特定的一天:

+----------+-------+------+------+------------+
| Filmname | time  | idFI | Lang | DateSZ     |
+----------+-------+------+------+------------+
| firstfi  | 12:00 | 22   | eng  | 2018-06-29 |
+----------+-------+------+------+------------+
| sencofi  | 15:00 | 44   | fra  | 2018-06-29 | 

秒:

SELECT 
    idFI, 
    COUNT(DISTINCT (case when Yweek < 201825 then Yweek end)) AS Week 
FROM `Timetable` 
GROUP BY idFI

给我

+-------+------+
| Week  | idFI |
+-------+------+
| 2     | 22   |
+-------+------+
| 1     | 44   |

我的时间表表看起来像这样(加上更多列):

+----------+-------+------+--------+------------+
| Filmname | time  | idFI | Yweek  | DateSZ     |
+----------+-------+------+--------+------------+
| firstfi  | 12:00 | 22   | 201825 | 2018-06-29 |
+----------+-------+------+--------+------------+
| firstfi  | 18:00 | 22   | 201824 | 2018-06-21 |
+----------+-------+------+--------+------------+
| firstfi  | 13:00 | 22   | 201823 | 2018-06-12 | 
+----------+-------+------+--------+------------+
| sencofi  | 15:00 | 44   | 201825 | 2018-06-29 |
+----------+-------+------+--------+------------+
| sencofi  | 18:00 | 44   | 201823 | 2018-06-12 |
+----------+-------+------+--------+------------+
| sencofi  | 10:00 | 44   | 201823 | 2018-06-13 |

我的问题是,如果我将count(distinct)插入到第一个select语句中,那么它将无法正常工作,因为它仅计算巫婆符合语句nr中所有where子句的行。 1.如何合并这些语句?

编辑: 来自@MKhalidJunaid的答案,但无法使用我的格式:

SELECT t2.*, t1.Lang, Filmname, ColFI, t3.Week DATE_FORMAT(DateSZ, '%d.%m.%y') AS DateSZ, TIME_FORMAT(TimeSZ, '%H:%i') AS TimeSZ
FROM Timetable t2
JOIN Contenttable t1 ON t2.idFI = t1.id
JOIN (
    SELECT idFI, COUNT(DISTINCT (case when Yweek < 201825 then Yweek end)) AS Week 
    FROM Timetable 
    GROUP BY idFI
) t3 ON t2.idFI = t3.idFI
WHERE DATE_ADD(STR_TO_DATE(CONCAT('201825',' Thursday'), '%x%v %W'), INTERVAL 0 DAY) = DateSZ 
AND RoomSZ =1 
AND deleteSZ = false 
ORDER BY TimeSZ

1 个答案:

答案 0 :(得分:1)

您可以将派生子选择用于计数查询,然后以第一个查询的身份加入

SELECT t2.*, t1.Lang, Filmname, ColFI , t3.Week
FROM Timetable t2
JOIN Contenttable t1 ON t2.idFI = t1.id
JOIN (
    SELECT idFI, COUNT(DISTINCT (case when Yweek < 201825 then Yweek end)) AS Week 
    FROM Timetable 
    GROUP BY idFI
) t3 ON t2.idFI = t3.idFI
WHERE DATE_ADD(STR_TO_DATE(CONCAT('201825',' Thursday'), '%x%v %W'), INTERVAL 0 DAY) = DateSZ 
AND RoomSZ =1 
AND deleteSZ = false 
ORDER BY TimeSZ

也不要为连接表使用旧语法,而是使用带有join关键字的显式语法