我一直在搜索,似乎无法弄清楚如何获取以下内容,非常赞赏的任何帮助!
鉴于这些表格:
TABLE_1
+-----------+----------+-------+
| firstName | lastName | zip |
+-----------+----------+-------+
| John | Doe | 80210 |
| Barty | Crouch | 80598 |
| Mary | Jane | 80233 |
| John | Doe | 80210 |
+-----------+----------+-------+
TABLE_2
+-----------+----------+-------+
| firstName | lastName | zip |
+-----------+----------+-------+
| John | Doe | 80210 |
| Barty | Crouch | 80598 |
| Max | Payne | 80233 |
+-----------+----------+-------+
如何选择表之间的匹配记录,其中Table_1中的记录只有一个结果?
像这样的东西(作为查询应该做的例子写出的最终部分是我无法弄清楚的)
SELECT Table_1.firstName,
Table_1.lastName,
Table_1.zip,
Table_2.firstName,
Table_2.lastName,
Table_2.zip
FROM Table_1, Table_2
WHERE Table_1.firstName = Table_2.firstName and Table_1.lastName = Table_2.lastName and Table_1.zip = Table_2.zip
and ONLY ONE RESULT First,Last,zip FROM TABLE_1
哪只会回归Barty Crouch 80598
答案 0 :(得分:3)
加入一个派生表,该表是table_1中只有1个组计数的行的分组列表。:
SELECT T2.FirstName, T2.LastName, T2.Zip
FROM TABLE_2 AS T2
JOIN (
SELECT T1.FirstName, T1.LastName, T1.Zip
FROM TABLE_1 AS T1
GROUP BY T1.FirstName, T1.LastName, T1.Zip
HAVING COUNT(*) = 1) AS T1
ON T1.FirstName = T2.FirstName
AND T1.LastName = T2.LastName
AND T1.Zip = T2.Zip
答案 1 :(得分:1)
许多可能的变体之一:
SELECT Table_1.firstName,
Table_1.lastName,
Table_1.zip
FROM Table_1, Table_2
WHERE Table_1.firstName = Table_2.firstName and Table_1.lastName = Table_2.lastName and Table_1.zip = Table_2.zip
group by table_1.firstname, table_1.lastname, table_1.zip
having count(*) = 1