SQL 内连接两个具有相同列名的表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3365494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:00:59  来源:igfitidea点击:

SQL inner join two tables with the same column names

sqlsqlite

提问by Steven smethurst

I have two tables with a variable amount of columns. (I don't know how many columns or what there names will be) for example Table A and Table B.

我有两个表,列数可变。(我不知道有多少列或名称是什么)例如表 A 和表 B。

TableA:

表A:

ID | B_ID | {variable} 

TableB

表B

ID | {variable} 

Query:

询问:

SELECT TableA.*, TableB.* FROM TableA INNER JOIN TableB ON TableA.B_ID= TableB.id;

When TableA and TableB both have a column with a same name I can't distinguish between the two different columns. For example of both tables has the column "Name" this query would result in :

当 TableA 和 TableB 都有一个同名的列时,我无法区分这两个不同的列。例如,两个表都有列“名称”,此查询将导致:

ID | ID | B_ID | NAME | NAME |
 1 | 35 | 35   | bob  | jim  |

What I am looking for is a way to differentiate between the two tables. Preferably with a prefex for the column names such as.

我正在寻找的是一种区分两个表的方法。最好带有列名的前缀,例如。

TableA_ID | TableB_ID | TableA_B_ID | TableA_NAME | TableB_NAME |
        1 |        35 |          35 |         bob |         jim |

I know of the "AS" keyword but the problem is that I don't know what the column names are going to be before hand. (I don't know if TableA or TableB are going to have the column Name)

我知道“AS”关键字,但问题是我事先不知道列名是什么。(我不知道 TableA 或 TableB 是否会有列名称)

So my question is

所以我的问题是

How do you differentiate the columns between the two tables with a INNER JOIN when the tables may have the same column names ?

当表可能具有相同的列名时,如何使用 INNER JOIN 区分两个表之间的列?

I am using SQLite3.

我正在使用 SQLite3。

采纳答案by AllenG

Your result set (given your query) should have all of the TableA columns followed by all the TableB colums, so when you get to the second IDcolum, you know you're into the TableB data.

您的结果集(给定您的查询)应该包含所有 TableA 列,后跟所有 TableB 列,因此当您到达第二ID列时,您知道您进入了 TableB 数据。

That said, it is would seem odd to me that you're querying all the data out of two tables about which you know functionally nothing...

也就是说,对我来说,您从两个表中查询所有数据,而您在功能上一无所知,这对我来说似乎很奇怪......

回答by MPelletier

This is admittedly a hack solution, but this:

这无疑是一个黑客解决方案,但这个:

SELECT TableA.*, "#", TableB.* 
FROM TableA INNER JOIN TableB ON TableA.B_ID= TableB.id;

Would produce a list of results which would be divided in two blocks, left and right of the # column.

将生成一个结果列表,该列表将分为两个块,# 列的左侧和右侧。