恐怕我问错题目了.
我在数据库中有两个表,它们与这个问题有关。
产品
类别
我需要创建两个查询。
一是获得product_category = 1、product_category = 2和product_category = 3的产品标识.
第二种方法是让products id有product_category = 1或product_category = 2或product_category = 3 .
我已经尝试了我学到的所有东西,但是没有任何效果,我应该使用什么样的查询?
编辑:
以下是一些示例行和预期结果
产品
ID | Name
------------
1 | Prod_3
------------
2 | Prod_4
------------
3 | Prod_5
------------
4 | Prod_6类别
ID | ProductID | CategoryID
----------------------------
1 | 1 | 101
----------------------------
2 | 1 | 102
----------------------------
3 | 1 | 103
----------------------------
4 | 2 | 102
----------------------------
5 | 2 | 103
----------------------------
6 | 2 | 108
----------------------------
7 | 3 | 121
----------------------------
8 | 3 | 111我想从Name表中选择Products。此产品应位于Categories表中,并具有特定的CategoryID。
Example1:
Select `ID`, `Name` From `Products`
WHERE IN `Categories`.`ProductID` = `Products`.`ID`
AND (`Categories`.`CategoryID` = 103 AND `Categories`.`CategoryID` = 102)这应导致:
ID | Name
------------
1 | Prod_3
------------
2 | Prod_4Example2:
Select `ID`, `Name` From `Products`
WHERE IN `Categories`.`ProductID` = `Products`.`ID`
AND (`Categories`.`CategoryID` = 108 OR `Categories`.`CategoryID` = 121)这应导致:
ID | Name
------------
2 | Prod_4
------------
3 | Prod_5发布于 2018-11-23 02:28:26
听起来你需要这样的东西:
select distinct p.ID, p.Name
from Products P
inner join Categories C on c.ProductId = p.ID
where c.CategoryID in (108, 121)发布于 2018-11-23 02:54:44
您可以使用group by和having获取所有类别的产品:
select p.ID, p.Name
from products p join
categories c
on c.productid = p.id
where c.categoryid in (102, 103)
group by p.id, p.name
having count(*) = 2; -- number of items in the `in` list发布于 2018-11-24 10:13:49
最后我得到了:
SELECT a.product_id FROM `product_categories` a
INNER JOIN (SELECT * FROM product_categories WHERE category_id = 1655) a1 ON
a1.product_id = a.product_id
INNER JOIN (SELECT * FROM product_categories WHERE category_id = 1605) a2 ON
[...]
a2.product_id = a.product_id
WHERE a.category_id = 1575https://stackoverflow.com/questions/53438307
复制相似问题