选择仅具有一个ID的行

时间:2013-03-05 01:08:14

标签: mysql sql

我有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,而这正是我想要完成的。

2 个答案:

答案 0 :(得分: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表。

答案 1 :(得分:-1)

SELECT Knowledge.*, Sorting.*
FROM Knowledge, Sorting 
WHERE Knowledge.id = Sorting.KID
group by kID
having count(id) < 2

问题是你在错误的字段上做了count()