gpt4 book ai didi

php - 具有重复列名的 MySQL JOIN 表

转载 作者:行者123 更新时间:2023-11-29 04:18:22 24 4
gpt4 key购买 nike

加入两个表后,我有重复的列名。如何区分名称并在 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";

最佳答案

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

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

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

关于php - 具有重复列名的 MySQL JOIN 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33531324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com