简体   繁体   中英

MySQL Many-To-Many Select - Best practice

I am looking for a best practice to get all News_IDs with three categories attached.

-- Table: news_categories
    +-------------+---------+
    | category_id | news_id |
    +-------------+---------+
    |           2 | 2       |
    |           2 | 3       |
    |           7 | 3       |
    |          14 | 2       |
    |           2 | 4       |
    |          12 | 3       |
    |          12 | 2       |
    +-------------+---------+

This is my SQL so far:

SELECT DISTINCT a.news_id
    FROM news_categories a, news_categories b, news_categories c
    WHERE 
    a.news_id = b.news_id AND b.news_id = c.news_id
    AND a.category_id =2
    AND b.category_id =7
    AND c.category_id =12

The query returns the news_id 3 which is what I want, but is this the way to go? How about performance when having even more categories to join?

To eliminate joins, group by the news_id and count the category_ids. If the number of category ids is how many you're looking for, you found them.

SELECT news_id, COUNT(category_id)
FROM t1_news_categories
WHERE category_id IN (2, 7, 12)
GROUP BY news_id
HAVING COUNT(category_id) = 3

Just to add something about performance here, I'm not sure how much faster this is versus your original query. Once you start adding more categories (joins) in the original query, though, then I think this will definitely be faster. It will also be easier to code than trying to dynamically create a query based on how many categories you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM