我有两个表,一个用于销售人员,一个用于乐队成员。我需要列出 sales people who represent members who ARE NOT in california
销售人员表
+---------+-----------+----------+
| salesid | firstname | lastname |
+---------+-----------+----------+
| 1 | Bob | Bentley |
| 2 | Lisa | Williams |
| 3 | Clint | Sanchez |
| 4 | Scott | Bull |
+---------+-----------+----------+
成员表
+---------+-----------+-----------+--------+
| salesid | firstname | lastname | region |
+---------+-----------+-----------+--------+
| 2 | Bryce | Sanders | NC |
| 3 | Marcellin | Lambert | VA |
| 3 | Caroline | Kale | VA |
| 1 | Kerry | Fernandez | VA |
| 2 | Roberto | Alvarez | IN |
| 1 | Mary | Chrisman | IN |
| 3 | Carol | Wanner | TX |
| 2 | Warren | Boyer | TX |
| 1 | Bonnie | Taft | VT |
| 3 | Terry | Irving | GA |
| 2 | Louis | Holiday | IL |
| 2 | Michelle | Henderson | GA |
| 3 | Bobby | Crum | VT |
| 2 | Tony | Wong | ONT |
| 2 | Vic | Cleaver | VT |
| 1 | Frank | Payne | NY |
| 1 | Roberto | Goe | OH |
| 1 | Jose | MacArthur | CA |
| 3 | Doug | Finney | GA |
| 3 | Brian | Ranier | ONT |
| 2 | William | Morrow | NY |
| 2 | Aiden | Franks | TX |
| 2 | Davis | Goodman | OH |
+---------+-----------+-----------+--------+
我试过了
SELECT a.firstname, a.lastname, b.region FROM salespeople a LEFT JOIN members b ON
b.region != "CA";
返回约88条记录,因为所有4名销售人员代表每个成员。这引出了我的下一个问题, I also need to list all salespeople who do not represent any members who are located in California
。我的查询有什么不同?
答案 0 :(得分:1)
SELECT b.firstname, b.lastname, GROUP_CONCAT(a.region) regions
FROM members a
LEFT JOIN salespeople b ON a.salesid = b.salesid
GROUP BY b.firstname,b.lastname
HAVING NOT FIND_IN_SET("CA", regions);
<强> SQLFIDDLE 强>
答案 1 :(得分:0)
这将为您提供不代表CA的销售人员。
SELECT a.firstname, a.lastname, b.region FROM salespeople a LEFT JOIN members b
ON a.salesid = b.salesid where b.region != "CA"
and b.salesid NOT IN (select c.salesid from members c where b.region = "CA");
答案 2 :(得分:0)
SELECT a.firstname, a.lastname ,b.region
FROM salespeople a, members b
WHERE a.salesid = b.salesid
AND a.salesid NOT IN(
SELECT DISTINCT c.salesid
FROM members c
WHERE c.region = 'CA'
)
GROUP BY a.salesid,b.region
HAVING b.region !='CA'
这个答案没有使用join,希望对此有所帮助。
答案 3 :(得分:0)
SELECT
a.firstname,
a.lastname,
b.region
FROM salespeople a
LEFT JOIN members b ON a.salesid = b.salesid
WHERE b.region != "CA"