簡體   English   中英

mysql php使用相同的別名查詢相同的表5次,但每次使用該別名用於不同的列

[英]mysql php query same table 5 times using the same alias but use that alias for a different column each time

我有一個表,該表存儲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個selects進行測試,這比較容易,但是當我發現這一點時,我將查詢該表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";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM