mysql - 如何仅在列数超过一定数量时检索数据

标签 mysql sql

这是我的查询

SELECT news.*, count(followers.artist_id) as followers 
FROM news 
INNER JOIN followers ON news.artist_id = followers.artist_id 
GROUP BY followers.artist_id 
ORDER BY followers DESC

所以我目前正在获取按特定艺术家的关注者数量排序的所有新闻。

我想做的是仅在关注者超过一定数量(例如 10)时检索新闻。

所以我尝试加入一个 where 子句

WHERE followers > 10

但是我收到一个错误,指出 where 子句中没有这样的列。

我可以做什么来实现这个目标?我可以制作一个包含关注者数量的假专栏吗?

干杯

最佳答案

试试这个:

SELECT news.*, x.[followers]
FROM news
INNER JOIN (
    SELECT news.id, Count(followers.id) as [followers]
    FROM news 
    INNER JOIN followers ON news.artist_id = followers.artist_id 
    GROUP BY news.id
    HAVING Count(followers.id) > 10) as x on x.id = news.id

我假设两个表(新闻和关注者)都有唯一标识该行的 id 列。

关于mysql - 如何仅在列数超过一定数量时检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19876853/

相关文章:

php - mysqli_query 返回 false,因为值包含空格字符

mysql - Play framework 2.0.1 不断尝试进化错误的数据库类型

php - 为什么要编写 MySQL 查询 "programmatically like active record?"

sql - 如何执行与排序字段无关的查询?

sql - 如何连接上个月缺少行的两个表?

php - 使用空值/无值更新 INT/DECIMAL 字段

mysql - 如何使用提供程序在 Laravel 5.6 中按降序获取数据

PHP-替换字符串中的字符

sql - Redshift 左外连接忽略空值

c# - 在查询中参数化 WHERE 子句