简体   繁体   English

MySQL:如果表2中表1中的记录计数为0或1,则将其添加到表3中

[英]MySQL: Add to table3 if record from table1 has a count of 0 or 1 in table 2

Basically I'm trying to build a table (we'll call it table3) that has only the records from table1 that have counts of 0, 1, or do not appear at all in table2. 基本上,我试图构建一个表(我们将其称为table3),该表仅包含table1中的计数为0、1或根本不出现在table2中的记录。 Table1 and table3 are in database1 and table2 is in database2. 表1和表3在数据库1中,表2在数据库2中。

Here is the closest I can get to getting this working. 这是我能得到的最接近的解决方案。

INSERT INTO database1.table3 (col1, col2, ...)
SELECT t1.col1, t1.col2, ...
FROM database1.table1 AS t1
LEFT JOIN database2.table2 AS t2 ON t1.columnToMatch = t2.columnToMatch
WHERE (t2.count < 2);

TLDR: I want everything from table1 that doesn't appear in table2 to be added to table3. TLDR:我希望将table1中未出现在table2中的所有内容添加到table3中。 If the record in table1 appears in table2 I only want to include it in table3 if table2.count is 0 or 1. 如果table1中的记录出现在table2中,则仅在table2.count为0或1时才将其包括在table3中。

Thank you 谢谢

Welcome to SO. 欢迎来到SO。

You are looking for an LEFT EXCLUDING JOIN - see here 您正在寻找LEFT EXCLUDING JOIN - 看到这里

To get all records from table1 that doesn't appear in table2 do a 要从table1中获取未在table2出现的所有记录,请执行

SELECT table1.* 
FROM table1 
LEFT JOIN table2
ON table1.columnToMatch = table2.columnToMatch 
WHERE table2.columnToMatch IS NULL

After that get all matchting records with Count 0 or 1: 之后,获取所有匹配计数为0或1的记录:

SELECT table1.*
FROM database1.table1 AS t1
INNER JOIN database2.table2
ON table1.columnToMatch = table2.columnToMatch
WHERE table2.count IN (0, 1)

Then you can append both results with a UNION ALL and store the whole bunch in a new table: 然后,您可以将两个结果都附加一个UNION ALL并将整堆存储在新表中:

CREATE TABLE table3
SELECT ... FROM ...
UNION ALL
SELECT ... FROM ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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