Mysql子查询选择所有id

时间:2013-06-28 10:19:02

标签: mysql sql select group-by inner-join

所以,我需要帮助在子查询中做一个选择,我知道这有点基础,但我还是不能自己做。

(Reparacao =维修和lojas =商店,从葡萄牙语到英语)

我想获得每家商店的维修数量。但是我一次只能做一个商店,但我想要一个选择所有商店的查询。

我正在使用此查询:

SELECT COUNT( DISTINCT id_reparacao ) , lojas.nome
FROM reparacoes
INNER JOIN lojas ON lojas.id = 1
WHERE id_loja = lojas.id

我想要这样的东西:

SELECT COUNT( DISTINCT id_reparacao ) , lojas.nome
FROM reparacoes
INNER JOIN lojas ON lojas.id = (Select id from lojas)    //i want the id of every store
WHERE id_loja = lojas.id

2 个答案:

答案 0 :(得分:1)

试试这个:

无需使用子查询来获取商店的所有修复计数。 您可以使用 JOIN GROUP BY 轻松获得结果。

SELECT COUNT(DISTINCT id_reparacao) repairCnt, lojas.nome
FROM reparacoes
INNER JOIN lojas ON lojas.id = id_loja 
GROUP BY lojas.id 

答案 1 :(得分:0)

为什么不尝试加入ON ID:

SELECT COUNT( DISTINCT r.id_reparacao ) , lojas.nome
FROM reparacoes r
INNER JOIN lojas l ON l.id = r.id_loja;