简体   繁体   English

MySQL只用MySQL获得结果

[英]MySQL get results with MySQL only

Say I had a MySQL table as pictured below, and I wanted to find any product_id 's which have the filters 2 AND 5 (so in the table this would be the product_id of 30), is this possible in MySQL? 说我有一个MySQL表,如下图所示,我想找到任何product_id的具有过滤器2和5(所以在表中,这将是30 PRODUCT_ID),这可能在MySQL? Or would I have to get product id's where the filter_id is 2 OR 5, and sort it in PHP? 或者我必须获取filter_id为2或5的产品ID,并在PHP中对其进行排序?

sql表

SELECT product_id, COUNT(*) AS i FROM mytable WHERE filter_id IN (2,5) GROUP BY product_id HAVING i = 2;

This will match any rows containing any of the required filter_ids and group together those with the same product_id. 这将匹配包含任何所需filter_id的任何行,并将具有相同product_id的行组合在一起。 The name i has been given to a column giving the number of rows in the group. 名称i已被赋予给出组中行数的列。 Assuming that every combination of product_id to filter_id will be unique then you know that any group with two rows will have matched both of the filter_ids, so the HAVING clause will finally filter out the rows that only matched one of the filter_ids. 假设product_id与filter_id的每个组合都是唯一的,那么您就知道任何具有两行的组都将匹配两个filter_id,因此HAVING子句最终将过滤掉仅匹配其中一个filter_id的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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