MySQL - 如何在同一列上创建多于1个where子句?

时间:2013-03-23 21:22:33

标签: mysql

我正在尝试多次在同一列上创建where子句,例如:

  product
----------------------------------------
| product_id | product_name | group_id |
----------------------------------------

  group
-------------------------
| group_id | group_name |
-------------------------

  group_val
-------------------------
| group_id | product_id |
-------------------------


select b.product_name
from group_val a
inner join product b using(product_id) 
inner join group c using(group_id) 
where a.group_id in(10,15,88)
group by b.product_id;

它与or ... or相同,但我需要做类似的事情:它只返回组10,组15和组88的产品:我的意思是产品需要在这3组中。< / p>

即:

  group_val
-------------------------
| group_id | product_id |
-------------------------
| 10       | 1          |
-------------------------
| 15       | 1          |
-------------------------
| 88       | 1          |
-------------------------
| 15       | 2          |
-------------------------
| 10       | 2          |
-------------------------

在这种情况下,它只会返回产品1

我该怎么做?

2 个答案:

答案 0 :(得分:0)

表格产品

中不需要字段group_id
SELECT p.product_name
  FROM product AS p
    INNER JOIN group_val AS g1 ON p.product_id = g1.product_id
    INNER JOIN group_val AS g2 ON p.product_id = g2.product_id
    INNER JOIN group_val AS g3 ON p.product_id = g3.product_id
  WHERE g1.group_id = 10 AND g2.group_id = 15 AND g3.group_id=88;

SQL Fiddle

中试用

答案 1 :(得分:0)

只需处理您的示例查询,并假设您明确地以编程方式或其他方式知道,group_id您希望匹配哪些内容以及有多少内容:

select `product_name`, count(gv.`product_id`) as cnt
from `product` p
left join `group_val` gv
on p.`product_id` = gv.`product_id`
where gv.`group_id` in (10, 15, 88)
group by p.`product_id`
having cnt = 3;

将选择所有这些群组中product_id中的所有group_val