我有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
出于某种原因,它仍会返回所有内容,而不仅仅是Hi
和Jump
,而这正是我想要完成的。
答案 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;
子查询将仅返回sorting
表中具有单个计数的那些行,然后您可以使用此结果加入knowledge
表。
答案 1 :(得分:-1)
SELECT Knowledge.*, Sorting.*
FROM Knowledge, Sorting
WHERE Knowledge.id = Sorting.KID
group by kID
having count(id) < 2
问题是你在错误的字段上做了count()