如何在每个键上有多个记录的表上执行此连接而不返回每个键的多个记录?

时间:2017-10-24 14:59:40

标签: sql oracle plsql

我有三个表需要连接在一起,tableA,tableB和tableC。

tableA和tableB在字段“userid”上连接在一起,tableC在“numeric_id”上加入。

我的问题是tableC中有每个numeric_id有多个记录。如何通过不同的numeric_id列表限制查询?

此查询按预期返回23行:

SELECT * FROM tableA, tableB 
WHERE PRODUCT_CODE = 'AS432'
AND tableA.userid = tableB.userid

此查询返回52行,因为每个numeric_id在tableC中都有多个记录

SELECT * FROM tableA, tableB,tableC
WHERE PRODUCT_CODE = 'AS432'
AND tableA.userid = tableB.userid
AND tableB.numeric_id = tableC.numeric_id

如何在不返回tableC中每个numeric_id的多个记录的情况下执行此连接?

示例数据:

tableA:
userid        first_name
jsamsonite    John
sjohnson      Sam
hpulaski      Harry

tableB的:

userid      last_name numeric_id
jsamsonite  Samsonite 56 
sjohnson    Johnson   57
hpulaski    Pulaski   58

表C:

numeric_id transaction_number region_group
56           56345            789
56           89848            789
57           89800            987
57           52355            987
57           49939            987
58           49892            398

理想情况下,查询将返回

tableA.userid tableA.first_name tableB.userid tableB.last_name tableB.numeric_ID tableC.numeric_id tableC.region_group
jsamsonite    John               jsamsonite    Samsonite   56    56    789
sjohnson      Sam                sjohnson      Johnson     57    57    987
hpulaski      Harry              Hpulaski      Pulaski     58    58    398

1 个答案:

答案 0 :(得分:0)

如果您只是限制数据而不是需要来自c的列,那么可能存在?而不是加入?

SELECT tableA.*, tableB.*
FROM tableA, tableB
WHERE PRODUCT_CODE = 'AS432'
  AND tableA.userid = tableB.userid
  AND EXISTS (SELECT * FROM tablec WHERE tableB.numeric_id = tableC.numeric_id)

或者只选择所需的重复列并使用不同的

SELECT * 
FROM tableA, tableB, (SELECT DISTINCT col1, Col2, numeric_ID from tablec) tablec
WHERE PRODUCT_CODE = 'AS432'
  AND tableA.userid = tableB.userid
  AND tableB.numeric_id = tableC.numeric_id)

或使用现代连接语法... ANSI-92标准。但仍然在子查询上有明显的与c。列相似的值。

SELECT * 
FROM tableA
INNER JOIN tableB
  on  tableA.userid = tableB.userid
INNER JOIN (SELECT DISTINCT col1, Col2, numeric_ID from tablec) tablec
  on  tableB.numeric_id = tableC.numeric_id
WHERE PRODUCT_CODE = 'AS432'