我有两个数据库表,如下所示:

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表中选择有一个孩子出现的行,这就是我所尝试的:
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这正是我想要完成的。

最佳答案

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

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表。

关于mysql - 选择仅出现一次ID的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15214062/

10-10 18:53