簡體   English   中英

SQL篩選器條目與另一個表中的所有條目匹配

[英]SQL filter entries which match all entries from another table

我正在使用MySQL。 假設我有以下兩個表:

table 1
+---------+
| product |
+---------+
|       1 |
|       2 |
+---------+

table2
+------+---------+
| name | product |
+------+---------+
| A    |       1 |
| A    |       2 |
| B    |       1 |
| B    |       3 |
| C    |       1 |
+------+---------+

使用以下代碼生成:

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);

我想生成一個表,其名稱來自table2,其產品與table1的所有產品匹配。 在這種情況下,

+------+
| name |
+------+
| A    |
+------+

這是所有產品與另一表中的產品匹配的零售商的名稱。

我可能看不到這很簡單。 我嘗試了內部聯接,將所有聯接與子查詢一起使用,但是...

您可以使用join獲取任何匹配項。 然后having檢查它們是否都在那兒。

假設沒有重復:

select t2.name
from table2 t2 join
     table1 t1
     using (product)
group by t2.name
having count(*) = (select count(*) from table1);

創建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

我最終能夠使用以下方法解決此問題:

SELECT nome
FROM table2
WHERE product IN (SELECT product FROM table1)
GROUP BY nome HAVING COUNT(*) = (SELECT COUNT(*) FROM table1);

基於檢查一列是否包含另一列的所有值-MySQL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM