不确定如何为上述任务构建sql查询

brqmpdu1  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(267)

这些是我的table:

concerts (
    concert_id: INT, 
    name: VARCHAR(200), 
    venue: VARCHAR(200), 
    schedule: DATETIME) 

singers (
    singer_id: INT, 
    name: VARCHAR(200), 
    gender: ENUM('male', 'female', 'other')) 

performances(singer_id: INT, 
    concert_id: INT) 
Foreign keys: {singer_id} to singers {concert_id} to concerts

我想提出一个查询,列出一个歌手在2018年的所有演唱会,他在5场以上的演唱会中都有演出(5和2018是由用户决定的变量/我正在测试这些变量)我尝试了多次尝试,但似乎没有什么能接近我试图实现的任务。如有任何帮助,我们将不胜感激。

v6ylcynt

v6ylcynt1#

在子选择查询(派生表)中,我们可以首先确定 singer_id 2018年有5场以上演唱会的value(s)。我们使用 Group ByCount(...) 函数,以确定 singer_id . 请注意,如果您的 singer_id 以及 concert_id 中的组合 performances 表,则需要使用 Count(Distinct ...) 功能。现在,我们可以使用 Having 子句只考虑计数大于5的歌手。
现在,简单地说 Join 此派生表将结果集设为主表,以便获得2018年的音乐会列表。
尝试以下查询:

SELECT c1.*, s1.*
FROM 
concerts AS c1 
JOIN performances AS p1 ON p1.concert_id = c1.concert_id 
JOIN 
(
  SELECT
    s.singer_id, 
    COUNT(c.concert_id) AS num_concerts 
  FROM 
    singers AS s 
  JOIN performances AS p ON p.singer_id = s.singer_id 
  JOIN concerts AS c ON c.concert.id = p.concert_id AND 
                        c.schedule >= '2018-01-01' AND 
                        c.schedule < '2019-01-01'
  GROUP BY s.singer_id 
  HAVING num_concerts > 5
) AS dt ON dt.singer_id = p1.singer_id 
JOIN singers AS s1 ON s1.id = dt.singer_id 
WHERE c1.schedule >= '2018-01-01' 
  AND c1.schedule < '2019-01-01'

相关问题