加入两个没有子查询的表

时间:2013-09-08 16:14:54

标签: mysql sql

我正在尝试创建没有子查询的sql查询,这里是工作查询:

select * from customers 
join 
(select idContactOwner, count(*) contacts_count 
from contacts GROUP BY idContactOwner HAVING contacts_count>5) k 
where customers.id=k.idContactOwner;

这就是我正在尝试的但是它不起作用:

select idContactOwner, count(*) counter from contacts A
group by idContactOwner having counter>5 join customers B
on A.idContactOwner=B.id;

这里是sql小提琴:

http://sqlfiddle.com/#!2/724962/59

2 个答案:

答案 0 :(得分:3)

group by必须在join

之后
select A.idContactOwner, count(*) counter 
from contacts A
join customers B on A.idContactOwner = B.id
group by A.idContactOwner 
having counter > 5 

答案 1 :(得分:1)

SELECT A.idContactOwner, B.whatEverFields, count(A.idContactOwner) AS counter
FROM contacts A, customers B
WHERE A.idContactOwner=B.id 
GROUP BY A.idContactOwner 
HAVING counter>5;

这样的东西?