1

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

4

2 回答 2

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
于 2013-05-03T20:03:51.553 回答
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
于 2013-05-03T20:03:46.707 回答