如何使这个mysql子查询工作

时间:2011-01-22 01:26:23

标签: sql mysql

SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN (

SELECT noreg
FROM register_keluar
)
AND (
c.idunit LIKE '20%'
)
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC

//错误是:AND jumlah> 1

3 个答案:

答案 0 :(得分:2)

jumlah > 1移到HAVING子句中,例如:

...
GROUP BY ...
HAVING jumlah > 1
ORDER BY ...

http://en.wikipedia.org/wiki/Having_(SQL):

  

SQL中的HAVING子句指定了这一点   只应该使用SQL SELECT语句   返回聚合值的行   符合规定的条件。

答案 1 :(得分:0)

尝试:

SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN ( SELECT noreg FROM register_keluar AND c.idunit LIKE '20%') 
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC

答案 2 :(得分:0)

当您组合任何列的选择和聚合别名(在您的示例中:COUNT(*)作为jumlah)然后您打算在查询中的某处使用此聚合别名(jumlah)时,使用 GROUP BY 条件,您需要在相应的GROUP BY之后使用 HAVING 条件。