Finding IDs Occurring in Specific Column Values on Multiple Rows
In a MySQL associative table, identifying items present in multiple specific categories poses a challenge. The initial approach using AND and OR operators is ineffective, as it does not account for the requirement of item presence in all specified categories.
To address this issue, a self-join technique can be employed:
<code class="sql">SELECT c1.item_id FROM item_category AS c1 INNER JOIN item_category AS c2 ON c1.item_id = c2.item_id WHERE c1.category_id = 201 AND c2.category_id = 202</code>
This method joins two rows in the table to create a single row in the result set, allowing the evaluation of multiple category conditions.
An alternative approach involves using GROUP BY:
<code class="sql">SELECT c.item_id, COUNT(*) AS cat_count FROM item_category AS c WHERE c.category_id IN (201,202) GROUP BY c.item_id HAVING cat_count = 2</code>
This query groups items by ID and counts the number of categories they belong to. The HAVING clause ensures that only items present in all specified categories are returned.
Both techniques offer efficient solutions for finding items on multiple rows with specific column values, with their performance varying based on the number of categories being queried.
The above is the detailed content of How to Find Items Present in Multiple Specific Categories in a MySQL Associative Table?. For more information, please follow other related articles on the PHP Chinese website!