3

我有 2 个如下所示的数据库表:

Knowledge
id          |        Title
--------------------------
3                     Hi
6                     Hello
7                     Yo
5                     Jump


Sorting
id          +        kID       
--------------------------
0           |         3
1           |         6
2           |         7
3           |         6
4           |         7
5           |         5

我正在尝试从Sorting表中选择仅出现一次 kID 的行,这就是我尝试过的:

SELECT Knowledge.*, Sorting.*
FROM Knowledge, Sorting 
WHERE Knowledge.id = Sorting.KID
GROUP BY Sorting.KID 
    HAVING COUNT(Sorting.KID)<2
ORDER BY Sorting.SortOrder
LIMIT 0,8

出于某种原因,它仍然返回所有内容而不是仅仅返回HiJump这就是我想要完成的。

4

2 回答 2

1

我建议使用子查询来获得结果:

select k.id, k.title
from knowledge k
inner join
(
  select kID
  from sorting
  group by kID
  having count(kID) < 2
) s
  on k.id = s.kid
LIMIT 0,8;

请参阅SQL Fiddle with Demo

子查询将仅返回表中具有单个计数的那些行sorting,然后您可以使用此结果连接到knowledge表。

于 2013-03-05T03:11:11.410 回答
-1
SELECT Knowledge.*, Sorting.*
FROM Knowledge, Sorting 
WHERE Knowledge.id = Sorting.KID
group by kID
having count(id) < 2

问题是您在错误的字段上执行 count()

于 2013-03-05T01:14:11.877 回答