在SQL中基于联接多个表进行过滤

编程入门 行业动态 更新时间:2024-10-28 16:28:24
本文介绍了在SQL中基于联接多个表进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用MySQL,并且有三个表:

I am using MySQL and I have three table:

Table: Salesperson ID | Name | Age | Salary 1 | Abe | 61 | 140000 2 | Bob | 34 | 44000 5 | Chris| 34 | 40000 7 | Dan | 41 | 52000 8 | Ken | 57 | 115000 11 | Joe | 38 | 38000 Table: Customer ID | Name | City | Industry_Type 4 | Samsonic | pleasant | J 6 | Panasung | oaktown | J 7 | Samony | jackson | B 9 | Orange | jackson | B Table: Orders Number | order_date | cust_id | salesperson_id | Amount 10 | 1996-08-02 | 4 | 2 |540 20 | 1999-01-30 | 4 | 8 |1800 30 | 1995-07-14 | 9 | 1 |460 40 | 1998-01-29 | 7 | 2 |2400 50 | 1998-02-03 | 6 | 7 |600 60 | 1998-03-02 | 6 | 7 |720 70 | 1995-05-06 | 9 | 7 |150

我想查找所有与Samsonic没有任何订单并且至少已下订单1的销售人员的姓名

I want to find the names of all salespeople that do not have any orders with Samsonic and who have made at least 1 order

我的预期结果是:

Name Abe Dan

我尝试过:

SELECT Distinct(s.name) FROM Orders o INNER JOIN Salesperson s ON o.salesperson_id = s.ID INNER JOIN Customer c ON c.ID = o.cust_id WHERE s.name NOT IN( select s.name where c.name='Samsonic' );

但是我得到的结果是:

Name Dan Bob Abe

我相信Bob出现了,因为他下达了另一个非Samsonic的订单.在仍然连接所有三个表的同时如何获得预期的结果?谢谢!

I believe Bob shows up since he made another order that was not Samsonic. How can I get my intended result while still joining all three tables? Thanks!

推荐答案

在子查询中,您正在引用外部查询中的表.

In your subquery, you are referencing tables in the outer query.

下面的代码应该可以解决您的问题.

The code below should fix your issue.

SELECT DISTINCT s.name FROM salesperson s INNER JOIN orders o ON s.id = o.salesperson_id INNER JOIN customer c ON o.cust_id = c.id WHERE s.name NOT IN ( SELECT s.name FROM salesperson s INNER JOIN orders o ON s.id = o.salesperson_id INNER JOIN customer c ON o.cust_id = c.id WHERE c.name = 'Samsonic' );

更多推荐

在SQL中基于联接多个表进行过滤

本文发布于:2023-10-27 18:19:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534159.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!