我目前有一個mysql聯合查詢,當通過命令行,PHP MyAdmin直接放入mysql或在Mysql編輯器(如Mysql Workbench)中運行時可以工作。當我通過我的PHP類運行查詢時,它返回兩個重複的行。PHP中的Mysql聯盟不返回正確的結果
查詢:
SELECT `n`.`draftrd`, `n`.`draftteam`, `n`.`nflteam`, `nt`.`logo`,
`nt`.`name`, `nt`.`nflcity`,
`p`.`class`, `p`.`first_name`, `p`.`last_name`
FROM `players` as `p`
LEFT JOIN `nfl` as `n` ON `p`.`playerid` = `n`.`playerid`
LEFT JOIN `nflteams` as `nt` ON `n`.`nflteam` = `nt`.`nflid`
WHERE `n`.`playerid` = 2007000001
UNION
SELECT `n`.`draftrd` as `draftRd`, `n`.`draftteam` as `draftTm`, `n`.`nflteam`,
`nt`.`logo`,
`nt`.`name` as `draftName`, `nt`.`nflcity` as `draftCity`, `p`.`class`,
`p`.`first_name`, `p`.`last_name`
FROM `players` as `p`
LEFT JOIN `nfl` as `n` ON `p`.`playerid` = `n`.`playerid`
LEFT JOIN `nflteams` as `nt` ON `n`.`draftteam` = `nt`.`nflid`
WHERE `n`.`playerid` = 2007000001
在它返回編輯:
+---------+-----------+---------+-------------+---------+----------+-------+------------+-----------+---------+
| draftrd | draftteam | nflteam | logo | name | nflcity | class | first_name | last_name | tableid |
+---------+-----------+---------+-------------+---------+----------+-------+------------+-----------+---------+
| 2 | 2 | 12 | giants.png | Giants | New York | 2007 | Martellus | Bennett | 1 |
| 2 | 2 | 12 | cowboys.png | Cowboys | Dallas | 2007 | Martellus | Bennett | 1 |
+---------+-----------+---------+-------------+---------+----------+-------+------------+-----------+---------+
2 rows in set (0.00 sec)
PHP的回報是: (該版本的var_dump)
array(18) {
[0]=> string(1) "2"
["draftrd"]=> string(1) "2"
[1]=> string(1) "2"
["draftteam"]=> string(1) "2"
[2]=> string(2) "12"
["nflteam"]=> string(2) "12"
[3]=> string(10) "giants.png"
["logo"]=> string(10) "giants.png"
[4]=> string(6) "Giants"
["name"]=> string(6) "Giants"
[5]=> string(8) "New York"
["nflcity"]=> string(8) "New York"
[6]=> string(4) "2007"
["class"]=> string(4) "2007"
[7]=> string(9) "Martellus"
["first_name"]=> string(9) "Martellus"
[8]=> string(7) "Bennett"
["last_name"]=> string(7) "Bennett"
}
我不知道問題是什麼以及爲什麼它不能正常工作。我試圖創建一個臨時表並將查詢存儲在它中,但它仍然給我重複的行。有沒有更簡單的方法來做到這一點或解釋爲什麼發生?我已經將查詢轉儲到PHP中,以查看問題是否與構造有關,但轉儲的查詢返回了我在命令行上運行時查找的行。
請嘗試格式化一遍... –
是啊,它肯定是在第一次運行難看。哈哈 – atxpunkrock
我不明白你說的「它是重複的」,如果你的意思是你有[3] => string(10)「giants.png」和[「logo」] => string(10) 「giants.png」這是因爲你可以使用數字索引(例如result [3])或文本索引(例如result [「logo」])訪問查詢結果 – Rafael