加入派生表时,列不能为空错误

时间:2013-05-03 19:59:47

标签: mysql sql sql-server

这是我的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 null并且喜欢0,这会在连接表时产生问题。另一个有趣的因素是,这个东西在我的本地服务器上工作文件,但不在我的实时服务器上。

2 个答案:

答案 0 :(得分:2)

您只能使用一个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

答案 1 :(得分:1)

尝试在内部查询中添加group by feed_id

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
                          group by feed_id) l
  on t1.id=l.feed_id where t1.id=12345