簡體   English   中英

新表中有兩列(table1 join table2),它們具有相同的列名,如何分別獲取兩者的值

[英]There are two columns in the new table(table1 join table2) which have the same column name, how to get the values of both respectively

select * from table1 join table2 on table1.column3=table2.column4 where ...
...
$row=mysql_fetch_assoc($result);

但是,新表中有兩列(表1和表2)具有相同的列名,如何分別獲取這兩個值?

用一個別名專門叫出列

SELECT table_1.id as table_1_id, table_2.id as table_2_id

您必須以這種方式列出至少一個表中的所有或大多數列,但是您可以跨多個表訪問具有相同名稱的cols。

select的列名前綴為其表名。

select table1.my_column, table2.my_column
from table1, table2
where table1.id = table2.t1_id

但是,使用這種方法時,您將不得不使用其返回的順序索引而不是其名稱來讀取列。 提到了使用as命名每個列的另一個答案,因此請考慮如果要按名稱讀取它們。

當由於查詢連接2個以上的表而導致列名沖突時,不能使用* 您可以使用:

SELECT table_1.*, 
       table_2.*
  FROM table_1, 
       table_2

如果那沒有返回您想要的列列表,則必須顯式列出每列。 沒有辦法-全有或全無。

表別名

...但是每次都要輸入完整的表名可能很麻煩,這就是為什么可以為表起別名的原因:

SELECT t1.*, 
       t2.*
  FROM table_1 AS t1, 
       table_2 t2

支持任何一種別名表示法。 如果您想將表聯接到自身,它們也是必需的。

最好只使用“選擇”列表中您實際需要的列名\\,但是,如果需要所有內容,那么繼續使用*:

Select a.*, 
       b.*, 
       a.id as a_id, 
       b.id as b_id,
       a.name as a_name,
       b.name as b_name
  from tablea a,
       tableb b
...

冗余不會造成傷害,因為a。*包含a_id和a_name,但是*中的值會丟失在關聯數組中,因此只需將它們重新添加為新的唯一名稱即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM