-1

好吧,我试图在同一列上多次创建 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;

它与第 10 组、第 15 组和第 88 组中的产品相同,or ... or但我需要执行以下操作:我的意思是产品需要在这 3 组中。

IE:

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

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

我该怎么做?

4

2 回答 2

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中尝试一下

于 2013-03-23T21:32:54.300 回答
0

只需使用您的示例查询,并假设您以编程方式或其他方式明确知道group_id您要匹配的 s 以及有多少:

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_ids 。group_val

于 2013-03-23T22:27:15.283 回答