How to differentiate between same field names of two tables in a select query?

限于喜欢 提交于 2019-11-28 10:20:18

问题


I have more than two tables in my database and all of them contains same field names like

table A           table B       table C
field1            field1        field1
field2            field2        field2
field3            field3        field3
.                 .             .
.                 .             .
.                 .             .
.                 .             .

I have to write a SELECT query which gets almost all same fields from these 3 tables. I am using something like this :

select a.field1,a.field2,a.field3,b.field1,b.field2,b.field3,c.field1,c.field2,c.field3 from table A as a, table B as b,table C as c where so and so.

but when I print field1's value it gives me the last table values.

How can I get all the values of three tables with the same field names? do I have to write individual query for every table OR there is any ways of fetching them all in a single query?


回答1:


Just write like this,

select a.field1 as af1,a.field2 as af2,a.field3 as af3,b.field1 as bf1,b.field2 as bf2,b.field3 as bf3,c.field1 as cf1,c.field2 as cf2,c.field3 as cf3 from table A as a, table B as b,table C as c where so and so.



回答2:


This is an artifact of how your programming tool handles duplicated field names. If you like, you can use AS to alias field names:

SELECT a.field1 AS a_field1, ...

It should then be accessible as a_field1.




回答3:


You can alias the columns. e.g. Note: The syntax can vary depending on your DB.

SELECT
    a.field1 `A_Field1`,
    b.field1 `B_Field1`

SELECT
    a.field1 [A_Field1],
    b.field1 [B_Field1]

SELECT
    a.field1 AS A_Field1,
    b.field1 AS B_Field1


来源:https://stackoverflow.com/questions/2800866/how-to-differentiate-between-same-field-names-of-two-tables-in-a-select-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!