将count(distinct)与复杂的select条件结合起来

jdg4fx2g  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(425)

我有两个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.1中所有where子句的行。我如何组合这些语句?
编辑:来自@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
7xllpg7q

7xllpg7q1#

您可以对count查询使用派生的sub select,然后将第一个查询作为

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关键字

相关问题