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

时间:2014-06-28 20:29:24

标签: php mysql union

我有一个表存储5个不同的网格坐标,我需要通过距离给定坐标的最短距离列出。所以我想我会使用union并在每次使用不同列的别名时查询表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";

我想要的结果是

player_name alliance_name级别优先级距离绳
     jon bad guys 10 high 4 1,1
     jon bad guys 10 high 6 2,2

我得到的是

player_name alliance_name级别优先级距离绳
     jon bad guys 10 high 4 1,1
     jon bad guys 10 high 6 1,1

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

请记住,我只使用2个选项进行测试,但是当我想出这个时我会查询表5次

1 个答案:

答案 0 :(得分:0)

首先,使用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";