简体   繁体   English

MySQL从子查询中分离出组子句

[英]MySQL break out group clause from subquery

Here is my query这是我的查询

SELECT 
    COALESCE(js.name,'Lead saknas'),
    count(j.id)
FROM 
    jobs j
LEFT JOIN
    job_sources js
    ON j.job_source=js.id
LEFT JOIN 
    (SELECT 
        * 
    FROM 
        quotes 
    GROUP BY 
        job_id) q 
    ON j.id=q.job_id
GROUP BY
    j.job_source

The problem is that it's allowed for each job to have more than one quote.问题是允许每个工作有多个报价。 Because of that i group the quotes by job_id.因此,我按 job_id 将引号分组。 Now sure, this works.现在可以肯定,这行得通。 But i don't like the solution with a subquery.但我不喜欢带有子查询的解决方案。 How can i break out the group clause from the subquery to the main query?如何将组子句从子查询分解到主查询? I have tried to add q.job_id to the main group clause, both before and after the existing one but don't get the same results.我试图将 q.job_id 添加到主组子句之前和之后,但没有得到相同的结果。

The GROUP BY in the subquery limits all results from quotes to 1 for a given job_id (MySQL will only return 1 result for each distinct grouping if you just do 'SELECT *', even if there are multiple rows that has that grouping), so you're joining jobs onto job_sources onto a table with only 1 row from quotes for each job_id.对于给定的 job_id,子查询中的 GROUP BY 将所有结果从引号限制为 1(如果您只执行“SELECT *”,MySQL 只会为每个不同的分组返回 1 个结果,即使有多个行具有该分组),所以您将job_sources 上的jobs 连接到一个表中,每个job_id 的引号中只有1 行。

What would happen when the GROUP BY is in the main query, is that it will join the 3 tables, then select 1 of them for each job_id.当 GROUP BY 在主查询中时会发生什么,它将连接 3 个表,然后为每个 job_id 选择其中的 1 个。

Since MySQL can return any 1 of multiple rows, obviously you cannot expect the results to be the same in every case.由于 MySQL 可以返回多行中的任意 1 行,显然您不能期望在每种​​情况下结果都相同。

If you were to use group functions it should return the same results (try something like SELECT COUNT(*), GROUP_CONCAT(quote_id) FROM quotes).如果您要使用组函数,它应该返回相同的结果(尝试诸如 SELECT COUNT(*)、GROUP_CONCAT(quote_id) FROM 引号之类的东西)。

MS SQL doesn't allow you just to do a 'SELECT *' when doing a GROUP BY (unless you GROUP BY all the fields, which is kind of pointless), since it can return different results for different queries. MS SQL 不允许您在执行 GROUP BY 时只执行 'SELECT *'(除非您对所有字段进行 GROUP BY,这是毫无意义的),因为它可以为不同的查询返回不同的结果。 Being allowed to do this in MySQL means you should know what you're doing.被允许在 MySQL 中执行此操作意味着您应该知道自己在做什么。

More specifically MS SQL does not allow you to select fields which you did not group on, unless you use grouping functions on them.更具体地说,MS SQL 不允许您选择未分组的字段,除非您对它们使用分组功能。

You are looking for a simple group by , I think:您正在寻找一个简单的group by ,我认为:

SELECT COALESCE(js.name,'Lead saknas'), count(j.id)
FROM jobs j LEFT JOIN
     job_sources js
     ON j.job_source=js.id
GROUP BY COALESCE(js.name,'Lead saknas')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM