我需要哪种类型的加入?
我有两张桌子、合同和推销员。 最近我发现数据中有一些错误,有些合同的 salesid 在“salesmen”中找不到,我怀疑是意外删除或某种输入错误。
我应该使用哪个连接来查找所有不“属于”销售员的合同,换句话说,在 salesmen.id 列中找不到contract.salesid。
它应该是一个右外连接,但结果并不正确。
I have 2 tables, contracts and salesmen.
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.
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.
It should be a right outer join but the results arent coming up right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
听起来你正在寻找“反加入”。 解释扩展 讨论了在 MySQL 中执行此操作的三种方法:
WHERE __ IS NULL
的左连接NOT IN
子句。NOT EXISTS
子句。Sounds like you're looking for an "anti-join". Explain Extended talks about the three ways to do this in MySQL:
WHERE __ IS NULL
NOT IN
clause with a subselect.NOT EXISTS
clause with a subselect.如果您要查找在
salesmen.id
中找不到的contract.salesid
,则可以使用NOT IN()
而不是联接。上面的代码将返回
contracts
中salesid
与现有salesmen.id
不匹配的所有内容。在大型表上使用NOT IN ()
可能比使用JOIN
慢,但如果您的表不太大,那么通常是更直接的使用方法(在我看来)。If you're looking for
contract.salesid
not found in thesalesmen.id
, you can useNOT IN()
rather than a join.The above will return everything from
contracts
havingsalesid
that matches no existingsalesmen.id
. UsingNOT IN ()
on large tables can be slower than doing it with aJOIN
, but if your tables aren't too large it is usually a more straightforward method to use (in my opinion).我的猜测是。
would be my guess.
左外连接
如果您从合同加入到推销员编辑:订单方式错误
left outer join
if you are joining from contracts to salesmanedit: had order around the wrong way
外连接确实可以做到这一点,但为什么不简单地:
An outer join could indeed do it, but why not simply:
我想这就是答案:
I suppose this is the answer :