我试图从我的数据库中选择所有已经访问过我网站的ips,不止一次,至少每天一次,从本月开始,但我的SQL查询显示错误。我做错了什么?
SELECT ip,COUNT(ip) AS matches
FROM ipAll
WHERE DATE LIKE '%-12-%'
HAVING matches > '1'
GROUP BY ip
错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY ip
答案 0 :(得分:4)
HAVING
来自GROUP BY
:
SELECT ip, COUNT(ip) AS matches
FROM ipAll
WHERE DATE LIKE '%-12-%'
GROUP BY ip
HAVING matches > 1;
但是,您应该更像这样编写查询:
SELECT ip, COUNT(ip) AS matches
FROM ipAll
WHERE MONTH(DATE) = 12
GROUP BY ip
HAVING matches > 1;
不要在日期上使用LIKE
,因为使用本地国际化设置将日期转换为字符串(隐式)。这些可能会改变,只是打破代码。另外,不要在需要数字的地方使用字符串常量。
答案 1 :(得分:2)
错误是因为根据mysql文档,having子句必须在group by子句之后才能使用。
所以你的查询必须看起来像这样
SELECT ip,COUNT(ip) AS matches FROM ipAll WHERE DATE LIKE '%-12-%' GROUP BY ip HAVING matches > '1'
答案 2 :(得分:1)
SELECT ip, COUNT(ip) AS matches
FROM ipAll
WHERE DATE LIKE '%-12-%'
GROUP BY ip
HAVING matches > 1;