我从1周开始尝试这个,但我无法实施。我尝试了很多方法,但没有得到任何解决方案。 我将在下面解释:
options table:
+---------+-----------+------------+
| id | name | major |
+---------+-----------+------------+
| 1 | option 1 | 1 |
| 2 | option 2 | 1 |
| 3 | option 3 | 1 |
| 4 | option 4 | 0 |
| 5 | option 5 | 0 |
| 6 | option 6 | 0 |
+---------+-----------+------------+
items table
+---------+-----------+
| id | name |
+---------+-----------+
| 1 | item 1 |
| 2 | item 2 |
| 3 | item 3 |
+---------+-----------+
items_options
+---------+-----------+
| item_id |option_id |
+---------+-----------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 1 | 6 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 2 | 6 |
| 3 | 1 |
| 3 | 3 |
| 3 | 5 |
| 3 | 6 |
+---------+-----------+
因此,如果我选择items_options.option_id IN (1,3)
和options.major = 1
,
我明白了:
+---------+----------+
| item_id | name |
+---------+----------+
| 1 | item 1 |
| 2 | item 2 |
| 3 | item 3 |
+---------+----------+
但我应该得到以下内容:
+---------+----------+
| item_id | name |
+---------+----------+
| 3 | item 3 |
+---------+----------+
我实际上并不需要考虑不重要的选项,但是当我选择1,3时,我应该只得到第二个结果,如果它有额外的主要选项,那么它应该不在列表中。结果应该只包含确切的选项,而不是更多或更少的选项。
我试过的MySQL查询:
SELECT items.id,items.name FROM items
INNER JOIN items_options ON items_options.option_id = items.id
INNER JOIN options ON options.id = items_options.option_id
WHERE items_options.option_id IN (1,3) AND options.major = 1
GROUP BY items.id
我只有3个主要选项,所以我也尝试使用下面的选项。
最后HAVING COUNT(DISTINCT items_options.option_id) = 2
编辑1:
sqlfiddle: http://sqlfiddle.com/#!2/280bf3/1
答案 0 :(得分:1)
您需要将count(distinct option_id)
时option_id in (1,3)
与distinct option_id
总数进行比较,按major = 1
进行过滤。
执行此操作的一种方法是将COUNT
与CASE
:
SELECT items.id, items.name
FROM items
INNER JOIN items_options io ON io.item_id = items.id
INNER JOIN options o ON io.option_id = o.id AND o.major = 1
GROUP BY items.id
HAVING COUNT(DISTINCT
CASE WHEN io.option_id IN (1,3)
THEN io.option_id
END) = COUNT(DISTINCT io.option_id)