简体   繁体   English

在一对多关系中,我想找到满足许多特定条件的数据

[英]In a one-to-many relationship, i want to find data that satisfies all the specific conditions of many

Product Table产品表

id(pk)编号(pk) name名称
1 1个 example name1示例名称 1
2 2个 example name2示例名称 2

Attribute Table属性表

id(pk)编号(pk) product_id(fk)产品编号(fk) attr属性
1 1个 1 1个 new新的
2 2个 1 1个 blue蓝色的
3 3个 1 1个 car
4 4个 2 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:我可以提出两个解决方案:

  • We can run 2 sub queries, one for each attribute, and then return only the productID's which are in both result sets.我们可以运行 2 个子查询,每个属性一个,然后只返回两个结果集中的产品 ID。
  • We can count the number of line returned which contain "blue" or "new".我们可以计算返回的包含“blue”或“new”的行数。
    NB: If 2 lines are returned we assume that one is "blue" and one is "new".注意:如果返回 2 行,我们假设一行是“蓝色”,一行是“新”。 If your data could return 2 lines with the same PID and both "blue" this query would return a false positive.如果您的数据可以返回具有相同 PID 且均为“蓝色”的 2 行,则此查询将返回误报。 We could around this with a sub-query with DISTINCT but it would not be any simpler than solution 1.我们可以使用带有 DISTINCT 的子查询来解决这个问题,但它不会比解决方案 1 更简单。
 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个

db<>fiddle here db<> 在这里摆弄

'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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM