简体   繁体   English

我需要哪种类型的联接?

[英]Which type of join do I need?

I have 2 tables, contracts and salesmen. 我有2张桌子,合同和推销员。 Recently I've discovered some errors in the data, some contracts have salesid's not found in 'salesmen', I suspect an accidental deletion or an input error of some kind. 最近,我发现数据中有一些错误,有些合同的“销售员”中没有salesid,我怀疑是意外删除或某种输入错误。

Which join should I use to find all contracts that dont 'belong' to a salesman, in other words, the contract.salesid not found in the salesmen.id column. 我应该使用哪个联接来查找不“属于”销售人员的所有合同,换句话说,在salesmen.id列中找不到contract.salesid。

It should be a right outer join but the results arent coming up right. 它应该是正确的外部连接,但结果不会正确。

Sounds like you're looking for an "anti-join". 听起来您正在寻找“反加入”。 Explain Extended talks about the three ways to do this in MySQL: 解释扩展讨论在MySQL中执行此操作的三种方法:

  • A left join with a WHERE __ IS NULL 左连接带有WHERE __ IS NULL
  • A NOT IN clause with a subselect. 一个带有子选择的NOT IN子句。
  • A NOT EXISTS clause with a subselect. 一个带有子选择的NOT EXISTS子句。

If you're looking for contract.salesid not found in the salesmen.id , you can use NOT IN() rather than a join. 如果要查找在salesmen.id找不到的contract.salesid ,则可以使用NOT IN()而不是联接。

SELECT * FROM contracts WHERE salesid NOT IN (SELECT id FROM salesmen);

The above will return everything from contracts having salesid that matches no existing salesmen.id . 上面的代码将返回了从contracts具有salesid不匹配现有salesmen.id Using NOT IN () on large tables can be slower than doing it with a JOIN , but if your tables aren't too large it is usually a more straightforward method to use (in my opinion). 在大型表上使用NOT IN ()可能比使用JOIN进行操作要慢,但是如果表不是太大,则通常使用更直接的方法(我认为)。

left outer join if you are joining from contracts to salesman 如果您要从合同加入业务员,则left outer join

edit: had order around the wrong way 编辑:命令顺序错误

SELECT c.contract_id FROM contract c
LEFT OUTER JOIN salesmen s ON s.salesman_id = c.salesman_id
WHERE c.salesman_id IS NULL

would be my guess. 是我的猜测。

An outer join could indeed do it, but why not simply: 外部联接确实可以做到,但是为什么不简单:

select *
from contract c
where c.salesid not in (select s.id
                        from salesmen s)

I suppose this is the answer : 我想这就是答案:

select * from Contract c 
right outer join Salesmen s on (c.salesid = s.id)

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

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