[英]Trying to figure out how to write an SQL query to return the nonintersection of two tables for a mysql database, having trouble
Sorry for total noobishness, but I'm trying to write SQL for the following problem involving a mysql database and I'm at a loss. 对于完全noobishness抱歉,但我正在尝试编写SQL以解决涉及mysql数据库的以下问题而且我很茫然。
Here's the problem. 这是问题所在。 Given the following two tables:
给出以下两个表:
**Table1**
PID WEBSITE COMP_SITE KEYCODE SITE_TYPE KEYWORDS
14 google.com bing.com w3874yf8 alpha happy+campers
26 radio.com alice.com 98ygdsfg beta slip+slop
13 simon.com fat.org 98dfyg77 delta sunrise
**Table2**
PID WEBSITE KEYWORDS
14 google.com happy+campers
14 yahoo.com fat+albert
14 aol.com chump+change
I want a query to return EVERY row in Table1 for which there are NO rows in Table2 matching the same (ID,WEBSITE,KEYWORDS) chunk of the row. 我想要一个查询返回Table1中的每一行,其中Table2中没有行匹配该行的相同(ID,WEBSITE,KEYWORDS)块。 In the above example this query would return rows 2 and 3 of Table1 .
在上面的示例中,此查询将返回Table1的第 2行和第3行。
Note that no columns in either table containing individual values unique to the table, though the ID/WEBSITE/KEYWORDS chunk of a row will be unique. 请注意,任何一个表中的列都不包含对表唯一的单个值,尽管行的ID / WEBSITE / KEYWORDS块将是唯一的。
I feel I'm making this far more complicated than it need to be. 我觉得我做的比这要复杂得多。 :/
:/
select * from Table1 as t1
left join Table2 as t2
on t1.PID =t2.PID
and t1.WEBSITE =t2.WEBSITE
and t1.KEYWORDS = t2.KEYWORDS
where t2.PID is null
There are two common ways to approach this. 有两种常见的方法可以解决这个问题。 The first is a
left outer join
. 第一个是
left outer join
。 Use this construct to match all rows, keeping rows in the first table, and then filter out the ones with a match: 使用此构造匹配所有行,在第一个表中保留行,然后过滤掉匹配的行:
select t1.*
from table1 t1 left outer join
table2 t2
on t1.PID = t2.PID and
t1.WEBSITE = t2.WEBSITE and
t1.KEYWORDS = t2.KEYWORDS
where t2.PID is null;
The second method is not exists
: 第二种方法
not exists
:
select t1.*
from table1 t1
where not exists (select 1
from table2 t2
where t1.PID = t2.PID and
t1.WEBSITE = t2.WEBSITE and
t1.KEYWORDS = t2.KEYWORDS
);
Both these methods can take advantage of an index on table2
: 这两种方法都可以利用
table2
上的索引:
create index table2_PID_WEBSITE_KEYWORDS on table2(PID, WEBSITE, KEYWORDS);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.