[英]In a one-to-many relationship, i want to find data that satisfies all the specific conditions of many
Product Table产品表
id(pk)![]() |
name![]() |
---|---|
1 ![]() |
example name1![]() |
2 ![]() |
example name2![]() |
Attribute Table属性表
id(pk)![]() |
product_id(fk)![]() |
attr![]() |
---|---|---|
1 ![]() |
1 ![]() |
new![]() |
2 ![]() |
1 ![]() |
blue![]() |
3 ![]() |
1 ![]() |
car![]() |
4 ![]() |
2 ![]() |
new![]() |
In the above table, i want to find a specific product_id with both 'new' and 'blue' attributes(In this situation, expected value is product_id 1)在上表中,我想找到一个具有'new'和'blue'属性的特定product_id(在这种情况下,期望值为product_id 1)
select product_id form attrbute_table where attr in('new', 'blue')
did not give me the answer I was looking for没有给我想要的答案
I can propose two solutions:我可以提出两个解决方案:
create table attribute ( ID int primary key, PID int, attr VARCHAR(10));
✓✓
insert into attribute values (1,1,'new'), (2,1,'blue'), (3,1,'car'), (4,2,'new'), (5,3,'blue');
✓✓
SELECT a.PID FROM (SELECT PID, attr FROM attribute WHERE attr ='blue') a JOIN (SELECT PID,attr FROM attribute WHERE attr ='new') b ON a.PID = b.PID;
|| PID |
PID| |
| --: |
--: | |
| 1 |
1 |
SELECT PID product_id, COUNT(attr) num_found FROM attribute WHERE attr = 'blue' or attr = 'new' GROUP BY PID HAVING COUNT(attr) = 2;
product_id |产品编号 | num_found ---------: |
num_found ----------: | --------: 1 |
------: 1 | 2
2个
'i want to find a specific product_id with both 'new' and 'blue' attributes' '我想找到具有'new'和'blue'属性的特定product_id'
so you can use and condition所以你可以使用和条件
select product_id form attrbute_table where attr = 'new' and attr = 'blue'
The IN operator allows you to specify multiple values in a WHERE clause. IN 运算符允许您在 WHERE 子句中指定多个值。
The IN operator is a shorthand for multiple OR conditions . IN 运算符是多个 OR 条件的简写。 https://www.w3schools.com/sql/sql_in.asp
https://www.w3schools.com/sql/sql_in.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.