MySQL Select: Get Main Record(s) by Multiple Attached Records?
Not sure how to ask this so it makes sense, but I'm trying to do a query like:
SELECT * FROM PAGES WHERE an attached record exists in PAGE_FILTERS and that record has a FilterTypeID of 22 AND another attached record exists in PAGE_FILTERS for the same page ID and that record has a filter type id of 27.
I have a structure like this:
PAGES table PageID PageName 1 Page 1 2 Page 2 3 Page 3 PAGE_FILTERS table PageID FilterTypeID FilterValueID 1 22 1 1 27 2 2 22 0 2 24 1 3 22 1 3开发者_运维知识库 27 1 3 28 2
So, given FilterTypeID's of 22 and 27, my query should return PageID's 1 and 3. Page 2 doesn't get selected since 22 matches, but there's no record matching FilterTypeID 27.
Page 3 matches, even though there's an extra filter.
In other words, I know what filter types a page has to have, and I need to get all the pages that each have all the required types.
I'm not opposed to changing database structure if it makes more sense, but each page could have none, one, or many filter sets attached.
SELECT p.*
FROM pages p
JOIN PAGE_FILTERS pf
ON p.PageID = pf.PageID
AND pf.FilterTypeID IN (22,27)
GROUP BY p.PageID
HAVING COUNT(DISTINCT pf.FilterTypeID) = 2
精彩评论