简体   繁体   English

SQL SELECT语句 - 相同的列名

[英]SQL SELECT statement - same column names

Imagine I have the following SELECT statement which has been oversimplified. 想象一下,我有以下SELECT语句,它已被过度简化。

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

using php I run the following: 使用PHP我运行以下:

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

   echo $result["Name"];

}

this will give me the result of b.Name . 这会给我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.* . 我知道我可以使用a.Name AS aName, B.Name AS bName但是这有时可能会使您有长查询并且使用a.*复杂化。 I tried using $result["a.Name"] but it does not work. 我尝试使用$result["a.Name"]但它不起作用。 I am aware this works $result[0] but again this is not always possible without complicating things. 我知道这有效$result[0]但是如果没有复杂化的话,这并不总是可行的。

Is there any other way I can show a.Name please? 有没有其他方法可以展示a.Name请?

simple answer : no. 简单回答:没有。

long answer : the array index at PHP has to be unique. 答案很长:PHP的数组索引必须是唯一的。 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"] 然后你可以使用$result["aName"]$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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