简体   繁体   English

如何在没有 UNION 或 UNION ALL 的情况下组合多个 SQL 查询?

[英]How to combine multiple SQL Queries without UNION or UNION ALL?

There are 4 SELECT queries with JOIN consisting of different number of columns有 4 个 SELECT 查询,其中 JOIN 由不同数量的列组成

  • Table A1- 6 columns表格 A1- 6 列
  • Table A2 - 11 columns表 A2 - 11 列
  • Table A3 - 3 columns表 A3 - 3 列
  • Table A4 - 3 columns表 A4 - 3 列

Sample sql query of mine:我的示例 sql 查询:

SELECT * FROM Table A1 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT * FROM Table A2 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT * FROM Table A3 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT * FROM Table A4 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A';

This above query is returning error like this, ofcourse because there are mismatch in number of columns.上面的查询返回这样的错误,当然是因为列数不匹配。

ORA-01789: query block has incorrect number of result columns 01789. 00000 - "query block has incorrect number of result columns" ORA-01789: 查询块的结果列数不正确 01789. 00000 - “查询块的结果列数不正确”

Please let me know any ways to do without using UNION or UNION ALL.请让我知道不使用 UNION 或 UNION ALL 的任何方法。

You need to write column names, if one of the tables does not contain any of field that the field exists on another table you can use custom columns.您需要编写列名,如果其中一个表不包含该字段存在于另一个表上的任何字段,您可以使用自定义列。

Let's say that fieldC does not exist on TableA4;假设 TableA4 上不存在 fieldC;

SELECT fieldA, fieldB, fieldC FROM Table A1 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT fieldA, fieldB, fieldC FROM Table A2 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT fieldA, fieldB, fieldC FROM Table A3 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT fieldA, fieldB, NULL as fieldC FROM Table A4 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A';

We can also rename fields, but in this case we must be very careful about type and data compatibility;我们也可以重命名字段,但是在这种情况下我们必须非常小心类型和数据的兼容性;

SELECT someFieldA as fieldA, someFieldB as fieldB, someFieldC as fieldC FROM Table A1 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT fieldA, fieldB, fieldC FROM Table A2 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT fieldA, fieldB, fieldC FROM Table A3 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A'
UNION ALL
SELECT fieldA, fieldB, NULL as fieldC FROM Table A4 INNER JOIN table B ON B.fieldnaame = 'ABC' AND fieldname = 'A';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM