具有重复列名的MySQL JOIN表

时间:2015-11-04 20:24:44

标签: php mysql

连接两个表后,我有重复的列名。如何区分名称并在PHP中提取数据。

服务表:

+----+-------+--------+
| id | price | userID |
+----+-------+--------+
|  1 |   435 |     33 |
|  2 |   543 |     32 |
|  3 |  7646 |     33 |
|  4 |  7966 |     31 |
|  5 |   394 |     31 |
|  6 |   569 |     31 |
|  7 |   203 |     32 |
|  8 |   439 |     32 |
|  9 |   329 |     33 |
| 10 |   998 |     31 |
+----+-------+--------+

客户表:

+----+-------+-------+
| id | name  |  zip  |
+----+-------+-------+
| 30 | Joe   | 45698 |
| 31 | Bill  | 87848 |
| 32 | Cris  | 56879 |
| 33 | Sarah | 35411 |
| 34 | Nova  | 59874 |
| 35 | Lo    | 99874 |
+----+-------+-------+

使用此查询加入他们:

SELECT *
FROM services AS s, customers AS c
WHERE s.userID=c.id

加入表:

+----+-------+--------+----+-------+-------+
| id | price | userID | id | name  |  zip  |
+----+-------+--------+----+-------+-------+
|  1 |   435 |     33 | 33 | Sarah | 35411 |
|  2 |   543 |     32 | 32 | Cris  | 56879 |
|  3 |  7646 |     33 | 33 | Sarah | 35411 |
|  4 |  7966 |     31 | 31 | Bill  | 87848 |
|  5 |   394 |     31 | 31 | Bill  | 87848 |
|  6 |   569 |     31 | 31 | Bill  | 87848 |
|  7 |   203 |     32 | 32 | Cris  | 56879 |
|  8 |   439 |     32 | 32 | Cris  | 56879 |
|  9 |   329 |     33 | 33 | Sarah | 35411 |
| 10 |   998 |     31 | 31 | Bill  | 87848 |
+----+-------+--------+----+-------+-------+

当我运行这个脚本时,我想在id列中得到两个结果(例如第一行中的1和33):

$query =  "SELECT *
            FROM services AS s, customers AS c
            WHERE s.userID=c.id";

$result =  $link->query($query);

while($var = mysqli_fetch_array($result)) {

    print_r($var);

    //I would like to get them similar to this...
    //$id1 = $var['id'];
    //$id2 = $var['id'];
}

结果(注意两个id列都没有密钥。第一个是[0] => 1并且没有命名密钥):

Array ( [0] => 1 [id] => 33 [1] => 435 [price] => 435 [2] => 33 [userID] => 33 [3] => 33 [4] => Sarah [name] => Sarah [5] => 35411 [zip] => 35411 )

无论如何将密钥与不同的id相关联,而不对每个具有重复名称的列执行以下操作:

$query =  "SELECT *, c.id AS myNewID
            FROM services AS s, customers AS c
            WHERE s.userID=c.id";

1 个答案:

答案 0 :(得分:4)

您可以区分两者的唯一方法是使用AS来应用别名。例如,像这样:

SELECT s.id AS serviceID, c.id AS customerID
FROM services s
JOIN cusomters c ON c.id = s.userID;

这样,您可以稍后使用serviceIDcustomerID引用列,具体取决于实施方式。