0

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. 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.

4

2 回答 2

0

You are looking for a simple group by, I think:

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')
于 2012-11-21T15:24:52.207 回答
0

子查询中的 GROUP BY 将给定 job_id 的所有结果从引号限制为 1(如果您只执行 'SELECT *',MySQL 将只为每个不同的分组返回 1 个结果,即使有多个行具有该分组),所以您将作业加入到 job_sources 到一个表中,每个 job_id 的引号中只有 1 行。

当 GROUP BY 在主查询中时会发生什么,它将连接 3 个表,然后为每个 job_id 选择其中的 1 个。

由于 MySQL 可以返回多行中的任何 1 行,显然您不能期望结果在每种情况下都相同。

如果您要使用组函数,它应该返回相同的结果(尝试类似 SELECT COUNT(*), GROUP_CONCAT(quote_id) FROM quotes)。

MS SQL 不允许您在执行 GROUP BY 时只执行“SELECT *”(除非您对所有字段进行 GROUP BY,这有点毫无意义),因为它可以为不同的查询返回不同的结果。在 MySQL 中被允许这样做意味着你应该知道你在做什么。

更具体地说,MS SQL 不允许您选择未分组的字段,除非您对它们使用分组函数。

于 2012-11-21T11:19:03.573 回答