[英]SQL filter entries which match all entries from another table
I am using MySQL. 我正在使用MySQL。 Let's say I have these two tables:
假设我有以下两个表:
table 1
+---------+
| product |
+---------+
| 1 |
| 2 |
+---------+
table2
+------+---------+
| name | product |
+------+---------+
| A | 1 |
| A | 2 |
| B | 1 |
| B | 3 |
| C | 1 |
+------+---------+
which are produced using the following code: 使用以下代码生成:
CREATE TABLE table1(
product INT
);
CREATE TABLE table2(
name VARCHAR(10),
product INT
);
INSERT INTO table1 VALUES(1);
INSERT INTO table1 VALUES(2);
INSERT INTO table2 VALUES('A', 1);
INSERT INTO table2 VALUES('A', 2);
INSERT INTO table2 VALUES('B', 1);
INSERT INTO table2 VALUES('B', 3);
INSERT INTO table2 VALUES('C', 1);
I would like to produce a table with names from table2, for which its products match all products of table1. 我想生成一个表,其名称来自table2,其产品与table1的所有产品匹配。 In this case, simply
在这种情况下,
+------+
| name |
+------+
| A |
+------+
That's the name of the retailer for which all products match the ones in the other table. 这是所有产品与另一表中的产品匹配的零售商的名称。
This is probably something simple that I am failing to see. 我可能看不到这很简单。 I have tried inner joins, using all with a subquery, ... but...
我尝试了内部联接,将所有联接与子查询一起使用,但是...
You can use a join
to get any matches. 您可以使用
join
获取任何匹配项。 And then having
to check they are all there. 然后
having
检查它们是否都在那儿。
Assuming no duplicates: 假设没有重复:
select t2.name
from table2 t2 join
table1 t1
using (product)
group by t2.name
having count(*) = (select count(*) from table1);
create table3 then execute the following 创建table3然后执行以下命令
INSERT INTO table3 (name)
SELECT DISTINCT t2.name
FROM table2 t2
LEFT JOIN table1 t1 on t2.product = t1.product
WHERE t1.product IS NOT NULL
I ended up being able to solve this using: 我最终能够使用以下方法解决此问题:
SELECT nome
FROM table2
WHERE product IN (SELECT product FROM table1)
GROUP BY nome HAVING COUNT(*) = (SELECT COUNT(*) FROM table1);
Based on check if a column contains ALL the values of another column - Mysql 基于检查一列是否包含另一列的所有值-MySQL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.