我必须诚实地说,告诉你我不擅长数据库查询,而且这个问题可能很简单。
我有三张表
Post ID entry Category ID name CategoryBinding ID postID categoryID
我正常的查询是获取所有包含其类别的帖子
SELECT * FROM `Post` AS `p` LEFT JOIN `CategoryBinding` AS `cb` ON p.ID = cb.postID LEFT JOIN `Category` AS `c` ON cb.categoryID = c.ID
返回的查询与此类似:
ID entry ID name ID postID categoryID 1 entry1 1 php 1 1 1 1 entry1 2 asp 1 1 2 2 entry2 1 php 1 2 1 3 entry3 null null null null null
现在,我想获取属于某个类别ID的所有帖子,并将其放入该帖子的所有类别中。 IE浏览器我想得到与第一个查询相同的东西,但仅属于特定类别的帖子。现在,我只想获取属于asp类别的帖子。那是
ID entry ID name ID postID categoryID 1 entry1 1 php 1 1 1 1 entry1 2 asp 1 1 2
你知道我该怎么做吗?
如果有人帮助我,我将非常感激,因为这更像是“为我做工作”的问题。
SELECT * FROM Post AS p LEFT JOIN CategoryBinding AS cb ON p.ID = cb.postID LEFT JOIN Category AS c ON cb.categoryID = c.ID INNER JOIN Post AS p2 ON p.id = p2.id WHERE p.id in ( SELECT p2.id FROM Post as p2 LEFT JOIN CategoryBinding AS cb ON p2.ID = cb.postID LEFT JOIN Category AS c ON cb.categoryID = c.ID WHERE c.id = @SomeCategory )
Post
p
CategoryBinding
cb
Category
c
p2
好了,最后一枪。
这将返回重复的行,只需将一个group by添加到您想要的任何内容。