在多个连接操作之后按Count(*)分组

时间:2018-02-03 02:28:01

标签: mysql sql

试图找出我认为简单的查询 -

我有以下带有模式的表格如下。

models(id: int, first_name: string, last_name: string)

painters(id: int, first_name: string, last_name:string)

portraits_painters(painter_id: int, portrait_id: int)

roles(model_id: int, portrait_id: int)

我正在尝试满足此查询:名字,姓氏和计数 对于那些一直是他们自己的绘画模型的画家来说 - 即名字和姓氏的计数列是画家所做过的自画像(画家和模特)的数量。 (安全地假设相同的名字和姓氏代表同一个人)。

如果画家没有自画像,他们甚至不应该被包括在最终输出中。

SELECT
  models.first_name,
  models.last_name,
  COUNT(portraits_painters.portrait_id)
FROM models
RIGHT JOIN painters
  ON models.first_name = painters.first_name
  AND models.last_name = painters.last_name
RIGHT JOIN portraits_painters
  ON portraits_painters.painter_id = painters.id
RIGHT JOIN roles
  ON roles.portrait_id = portraits_painters.portrait_id
GROUP BY portraits_painters.portrait_id;

我基本上试图将表格缩小到名称匹配的行,然后是画家ID匹配且肖像ID匹配的实例,但显然我加入表格的方式有些不正确。 我在GROUP BY部分也遇到错误,所以不确定是否有更好的方法来处理它?也许是走样?

2 个答案:

答案 0 :(得分:1)

您可以使用以下方式获取模特和画家的名字:

select m.first_name, m.last_name, p.first_name, p.last_name
from roles r join
     portraits_painters pp
     on pp.portrait_id = r.portrait_id join
     painters p
     on p.id = pp.painter_id join
     models m
     on m.id = r.model_id;

剩下的就是wheregroup by

select p.first_name, p.last_name, count(*)
from roles r join
     portraits_painters pp
     on pp.portrait_id = r.portrait_id join
     painters p
     on p.id = pp.painter_id join
     models m
     on m.id = r.model_id
where m.first_name = p.first_name and m.last_name = p.last_name
group by p.first_name, p.last_name;

我不确定是什么思维会导致外连接或exists子句。

答案 1 :(得分:1)

  1. 获取所有肖像的画家信息:

    SELECT p.first_name, p.last_name, pp.portrait_id FROM portraits_painters AS pp JOIN painters AS p ON pp.painter_id = p.id

  2. 获取所有肖像的模特信息:

    SELECT m.first_name, m.last_name, pp.portrait_id FROM roles AS r JOIN models AS m ON m.id = r.model_id JOIN portraits_painters AS pp ON pp.portrait_id = r.portrait_id

  3. 在同一first_name和last_name上组合这两个表。现在你可以获得每幅肖像的画家信息和模特信息。只需按first_name和last_name对记录进行分组,然后为每个组分组COUNT,即可获得所需内容。

  4. 因此,最终的查询将是:

    SELECT a.first_name, a.last_name, COUNT(a.portrait_id) 
    FROM
      (
        SELECT p.first_name, p.last_name, pp.portrait_id 
        FROM portraits_painters AS pp 
        JOIN painters AS p 
        ON pp.painter_id = p.id
      ) AS a
    JOIN
      (
        SELECT m.first_name, m.last_name, pp.portrait_id 
        FROM roles AS r 
        JOIN models AS m ON m.id = r.model_id 
        JOIN portraits_painters AS pp ON pp.portrait_id = r.portrait_id
      ) AS b
    ON a.first_name = b.first_name AND a.last_name = b.last_name
    GROUP BY a.first_name, a.last_name;