这是我的 sql 查询:
select
t1.id, t1.text as text, l.likes as likecount
from
table1 as t1 left join (select feed_id, count(user_id) as likes
from likes
where feed_id=12345) l
on t1.id=l.feed_id where t1.id=12345
此查询仅获取一个特定的条目以及有多少人喜欢该条目。在此示例中,条目号为 12345。当条目至少有 1 个赞时,此查询工作正常。但是,当我为没有喜欢的条目运行此查询时,它会给出列提要不能为空的错误。
此错误的原因是内部查询返回一个 feed_id 为空的行并且喜欢 0,这在连接表时造成问题。另一个有趣的因素是这个东西在我的本地服务器上是工作文件,而不是在我的实时服务器上。
最佳答案
您只能使用一个 WHERE 子句:
select
t1.id, t1.text as text, l.likes as likecount
from
table1 as t1 left join (select feed_id, count(user_id) as likes
from likes
group by feed_id) l
on t1.id=l.feed_id
where t1.id=12345
您的子查询中不需要它,但您需要改用 GROUP BY 子句。
但是您可能可以使用以下方法简化上面的查询:
SELECT
t1.id, t1.text, COUNT(DISTINCT likes.user_id) likecount
FROM
table1 as t1 LEFT JOIN likes
ON t1.id = likes.feed_id
WHERE
t1.id = 12345
关于mysql - 连接派生表时列不能为空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16366639/