gpt4 book ai didi

php - mysql php使用相同的别名查询同一个表5次,但每次使用该别名用于不同的列

转载 作者:行者123 更新时间:2023-11-30 00:06:48 25 4
gpt4 key购买 nike

我有一个表,存储 5 个不同的网格坐标,我需要按距给定坐标的最短距离列出这些坐标。所以我想我会使用联合并查询表 5 次,每次使用不同列的别名。但似乎每个别名都返回第一个选择的值。这是我尝试过的查询。

SELECT floor(sqrt(pow((cord_1x-$cord1x),2)+pow((cord_1y-$cord1y),2))) as distance,
alliance_name, player_name, level, priority,cord_1x AS cordx, cord_1y AS cordy,
cord_2x, cord_2y, cord_3x, cord_3y, cord_4x, cord_4y, cord_5x, cord_5y
FROM cords
where alliance_id = " .$myalliance_id. " AND cord_1x <> '' AND active ='1'
UNION
SELECT floor(sqrt(pow((cord_2x-$cord1x),2)+pow((cord_2y-$cord1y),2))) as distance,
alliance_name, player_name, level, priority,cord_1x, cord_1y,
cord_2x AS cordx, cord_2y AS cordy, cord_3x, cord_3y, cord_4x, cord_4y, cord_5x, cord_5y
FROM cords
where alliance_id = " .$myalliance_id. " AND cord_2x <> '' and active ='1'
order by distance ASC";

我想要得到的结果是

玩家名称联盟名称等级优先距离线
乔恩坏人 10 高 4 1,1
乔恩坏人 10 高 6 2,2

我得到的是

玩家名称联盟名称等级优先距离线
乔恩坏人 10 高 4 1,1
乔恩坏人 10 高 6 1,1

看起来我使用的别名不正确。它不会将下一列的值应用于第一个选择中使用的相同别名。

请记住,我只使用了 2 个选择来进行测试,这更容易,但是当我弄清楚这一点时,我将查询表 5 次

最佳答案

首先,使用UNION ALL。您不希望 UNION 决定合并两个结果集行,因为它们是相同的。

其次,对于 UNION ALL 操作中的两个子查询,您应该按名称、数据类型和位置来调整列。您试图仅通过名称和数据类型来使它们一致。

也就是说,你需要这样的东西:

SELECT floor(sqrt(pow((cord_1x-$cord1x),2)+pow((cord_1y-$cord1y),2))) as distance,
alliance_name, player_name, level, priority,
cord_1x AS cordx, cord_1y AS cordy, /*alias columns */
cord_1x, cord_1y, cord_2x, cord_2y, /* cord_1 columns repeat */
cord_3x, cord_3y, cord_4x, cord_4y, cord_5x, cord_5y
FROM cords
where alliance_id = " .$myalliance_id. " AND cord_1x <> '' AND active ='1'
UNION ALL
SELECT floor(sqrt(pow((cord_2x-$cord1x),2)+pow((cord_2y-$cord1y),2))) as distance,
alliance_name, player_name, level, priority,
cord_2x AS cordx, cord_2y AS cordy, /* different alias columns */
cord_1x, cord_1y, cord_2x, cord_2y, /* cord_2 columns repeat */
cord_3x, cord_3y, cord_4x, cord_4y, cord_5x, cord_5y
FROM cords
where alliance_id = " .$myalliance_id. " AND cord_2x <> '' and active ='1'
order by distance ASC";

关于php - mysql php使用相同的别名查询同一个表5次,但每次使用该别名用于不同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24470687/

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