PHP中的Mysql Union没有返回正确的结果

时间:2012-12-03 20:26:39

标签: php mysql union

我目前有一个mysql Union查询,当通过命令行,PHP MyAdmin直接放入mysql或在像Mysql Workbench这样的Mysql编辑器中运行时,它可以正常工作。当我通过我的PHP类运行查询时,它返回两个重复的行。

查询:

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中转储查询以查看问题是否与它的构造有关,但转储查询返回我在命令行上运行时要查找的行。

1 个答案:

答案 0 :(得分:1)

PHP中的MySQL句柄允许您以不同的方式遍历结果数组。例如,您可以选择按键遍历关联数组(例如:echo $result['draftteam'];),也可以通过常规数组(例如:echo $result[2];)按索引进行迭代。

使用fetch_array()命令时,默认情况下,您同时获取这两种类型。这将产生你提供的文学作品。

如果您尝试根据查询创建动态表格(即:将每个列名称写入<th>,然后将其内容清空到下面的<td> s中),那么你应该使用fetch_assoc()命令,而不是fetch_array()命令。这只会返回数组中的文本键。

while($arr = mysqli_fetch_assoc($sql)) {
    foreach($arr as $key => $value){
        echo $key .' => '. $value .'<br />'."\n";
    }
}

http://php.net/manual/en/mysqli-result.fetch-assoc.php

http://php.net/manual/en/mysqli-result.fetch-array.php