我想知道这在SQL中是否可行。假设你有两个表A和B,你在表A上做一个选择,在表B上做一个连接:

SELECT a.*, b.* FROM TABLE_A a JOIN TABLE_B b USING (some_id);

如果表A有“a_id”、“name”、“some_id”列,表B有“b_id”、“name”、“some_id”列,查询将返回“a_id”、“name”、“some_id”、“b_id”、“name”、“some_id”列。有什么方法可以为表B的列名加上前缀而不单独列出每一列吗?等价于这个:

SELECT a.*, b.b_id as 'b.b_id', b.name as 'b.name', b.some_id as 'b.some_id'
FROM TABLE_A a JOIN TABLE_B b USING (some_id);

但是,如前所述,没有列出每一列,所以像这样:

SELECT a.*, b.* as 'b.*'
FROM TABLE_A a JOIN TABLE_B b USING (some_id);

基本上就是说,“用‘something’为b.*返回的每一列添加前缀”。这可能吗,还是我运气不好?

编辑

关于不使用SELECT *等的建议是有效的建议,但与我的上下文无关,因此请关注眼前的问题——是否可以在连接中为表的所有列名添加前缀(SQL查询中指定的常量)?

我的最终目标是能够通过连接对两个表执行SELECT *操作,并且能够从结果集中获得的列的名称中分辨出哪些列来自表a,哪些列来自表b。同样,我不想单独列出列,我需要能够执行SELECT *操作。


当前回答

I see two possible situations here. First, you want to know if there is a SQL standard for this, that you can use in general regardless of the database. No, there is not. Second, you want to know with regard to a specific dbms product. Then you need to identify it. But I imagine the most likely answer is that you'll get back something like "a.id, b.id" since that's how you'd need to identify the columns in your SQL expression. And the easiest way to find out what the default is, is just to submit such a query and see what you get back. If you want to specify what prefix comes before the dot, you can use "SELECT * FROM a AS my_alias", for instance.

其他回答

我知道的唯一一个这样做的数据库是SQLite,这取决于你使用PRAGMA full_column_names和PRAGMA short_column_names配置的设置。参见http://www.sqlite.org/pragma.html

否则,如果在查询中键入列名对您来说太麻烦的话,我所能建议的是通过序号位置而不是通过列名来获取结果集中的列。

这是一个很好的例子,说明了为什么使用SELECT *是不好的做法——因为最终您还是需要输入所有列名。

我理解需要支持可能更改名称或位置的列,但使用通配符会使这变得更加困难,而不是更容易。

我在PostgreSQL 13中使用to_jsonb函数来获得连接表中的所有字段作为一列。

select
  TABLE_A.*,
  to_jsonb(TABLE_B.*) as b,
  to_jsonb(TABLE_C.*) as c
from TABLE_A
left join TABLE_B on TABLE_B.a_id=TABLE_A.id
left join TABLE_C on TABLE_C.a_id=TABLE_A.id
where TABLE_A.id=1

结果你会得到TABLE_A列加上b和c列的数量:

id name some_other_col b c
1 Some name Some other value {"id":1,"a_id":1,"prop":"value"} {"id":1,"a_id":1,"prop":"value"}
1 Some other name Another value {"id":1,"a_id":1,"prop":"value"} {"id":1,"a_id":1,"prop":"value"}

您只需要解析b和c列以将它们转换为对象。

我和OP在同一条船上-我有来自3个不同表的数十个字段,我正在加入,其中一些具有相同的名称(即。身份证、姓名等)。我不想列出每个字段,所以我的解决方案是对共享名称的字段使用别名,并对具有唯一名称的字段使用select *。

例如:

表a: id, 的名字, field1, field2……

表b: id, 的名字, field3, field4……

选择a.id为aID, a.name为ame, a. *, b.id为bID, b.name为bName, b. * .....

当访问结果时,我们这些字段的别名和忽略“原始”名称。

也许不是最好的解决方案,但它为我工作....我用mysql

你可能会认为微软花了13年时间才把它装进去。它对于调试非常有用。 我已经养成了这样做的习惯:选择我认为我想要比较的列,然后在最后加上一个*来捕获我可能想要查看的任何其他内容。

选择a.breed, a.size, p.breed, p.size,a.,p。 源自动物 加入宠物p在a.breed=p.breed

不管怎样,你懂的。

或者你可以使用Red Gate SQL Refactor或SQL Prompt,它通过单击Tab按钮将SELECT *展开为列列表

所以在你的例子中,如果你输入SELECT * FROM A JOIN B… 转到*的末尾,Tab键,瞧!你会看到 选择a . columnn1, A.column2, ...., B. columnn1, B.column2 FROM A JOIN

但它不是免费的