简体   繁体   中英

SQL SELECT statement - same column names

Imagine I have the following SELECT statement which has been oversimplified.

SELECT a.Name, b.Name FROM table a LEFT JOIN table b ON a.ID=b.TID

using php I run the following:

while ($result = mysql_fetch_array($results)) {

   echo $result["Name"];

}

this will give me the result of b.Name . I am aware I can use a.Name AS aName, B.Name AS bName however this might sometimes complicate things where you have a long query and you use a.* . I tried using $result["a.Name"] but it does not work. I am aware this works $result[0] but again this is not always possible without complicating things.

Is there any other way I can show a.Name please?

simple answer : no.

long answer : the array index at PHP has to be unique. By this, the last similar name column will get the precedence.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.

source

However, you can solve this by using aliases.

SELECT a.Name as aName, b.Name as bName FROM table a LEFT JOIN table b ON a.ID=b.TID

then you can access the names from both tables by using $result["aName"] and $result["bName"]

Based on your requirements, you could consider dividing your query in to two fetch statements. This would allow you to have the duplicate column names.

SELECT a.* FROM table a LEFT JOIN table b ON a.ID=b.TID

SELECT b.* FROM table b LEFT JOIN table a ON a.ID=b.TID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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