mysql 其中 count(column_name) = 1?
这是我正在使用的查询:
SELECT k_id, COUNT(k_id) AS k_count
FROM template_keyword_link
WHERE k_id IN(1,2,3,4,5)
GROUP BY k_id;
此查询返回类似
1 | 6
2 | 1
3 | 4
4 | 1
5 | 9
我想添加类似 AND COUNT(k_id) = 1
的内容 所以我最终得到
2 | 1
4 | 1
但是我使用组函数无效。
我该怎么做呢?
Update:
我的问题的另一部分是。
这可以用作删除语句吗?
东西
DELETE FROM
template_keyword_link tkl
LEFT JOIN keywords k
ON tkl.k_id = k.k_id
WHERE tkl.k_id
IN(SELECT k_id, COUNT(k_id) AS k_count
FROM template_keyword_link
WHERE k_id IN(1,2)
GROUP BY k_id
HAVING k_count = 1);
像我得到的
您的 SQL 语法有错误;
So based on feedback i have altered this to use
DELETE tkl, k FROM
template_keyword_link tkl
LEFT JOIN keywords k
ON tkl.k_id = k.k_id
WHERE tkl.k_id
IN(SELECT k_id
FROM template_keyword_link
WHERE k_id IN(1,2)
GROUP BY k_id
HAVING COUNT(k_id) = 1);
然而现在我得到了
您无法在 FROM 子句中指定要更新的目标表“tkl”
Here is the query I am using:
SELECT k_id, COUNT(k_id) AS k_count
FROM template_keyword_link
WHERE k_id IN(1,2,3,4,5)
GROUP BY k_id;
This query returns something like
1 | 6
2 | 1
3 | 4
4 | 1
5 | 9
I want to add something like AND COUNT(k_id) = 1
so I end up with
2 | 1
4 | 1
However I get invalid use a group function.
How would I go about doing this?
Update:
The other part to my question is.
Can this be used as a delete statement?
something like
DELETE FROM
template_keyword_link tkl
LEFT JOIN keywords k
ON tkl.k_id = k.k_id
WHERE tkl.k_id
IN(SELECT k_id, COUNT(k_id) AS k_count
FROM template_keyword_link
WHERE k_id IN(1,2)
GROUP BY k_id
HAVING k_count = 1);
I get
You have an error in your SQL syntax;
So based on feedback i have altered this to use
DELETE tkl, k FROM
template_keyword_link tkl
LEFT JOIN keywords k
ON tkl.k_id = k.k_id
WHERE tkl.k_id
IN(SELECT k_id
FROM template_keyword_link
WHERE k_id IN(1,2)
GROUP BY k_id
HAVING COUNT(k_id) = 1);
However now I am getting
You can't specify target table 'tkl' for update in FROM clause
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
WHERE
子句在计算COUNT(*)
之前应用,因此您需要在HAVING
中应用它。另请参阅:http://dev.mysql.com/doc/refman/ 5.1/en/select.html
** UPD **:
TIAS ;-) 顺便说一句,查询语法对我来说似乎很好,但是你没有忘记吗指定
template_keyword_link
和keywords
连接条件子句? mysql 有没有给你任何错误?WHERE
clause is applied before theCOUNT(*)
has been calculated, so you need inHAVING
, that is applied after.See also: http://dev.mysql.com/doc/refman/5.1/en/select.html
** UPD **:
TIAS ;-) btw, the query syntactically seems fine for me, BUT did not you forget to specify
template_keyword_link
andkeywords
join condition clause? Does mysql give you any errors?您正在寻找发生的
having
子句after 分组(where
子句在分组之前):You're looking for the
having
clause which happens after grouping (thewhere
clause is before grouping):嵌套子查询是一个简单的解决方案。
Nested subquery is a simple solution.
试试这个
try this