UNION ALL是否返回一个数组?

时间:2009-10-24 00:42:48

标签: php sql

我有一个sql语句,它是多个查询的联合。

"SELECT a, b, c, 'd' as type FROM x WHERE id = $id UNION ALL
 SELECT a, b, c, 'e' as type FROM y WHERE id = $id UNION ALL
 SELECT a, b, c, 'f' as type FROM z WHERE id = $id ORDER BY a DESC LIMIT 10";

我尝试遍历结果并为每一行获取'a'值,但无法使其工作。

for($i =  0 ;  $i <  mysql_num_rows($result) ; $i++){
    $row = mysql_fetch_assoc($result);
    echo($row['a']);
}

我知道这是一个愚蠢的问题,但我被卡住了。 有什么想法吗? 谢谢!

4 个答案:

答案 0 :(得分:1)

解决。我将查询更改为此并且有效:

"SELECT a as A, b as B, c as C, 'd' as type FROM x WHERE id = $id UNION ALL
 SELECT a as A, b as B, c as C, 'e' as type FROM y WHERE id = $id UNION ALL
 SELECT a as A, b as B, c as C, 'f' as type FROM z WHERE id = $id ORDER BY a DESC LIMIT 10";

答案 1 :(得分:0)

您是否复制/粘贴了代码或重新输入代码?

$row = mysql\_fetch\_assoc($**g**uery);

想想看,你应该在结果句柄上调用mysql\_fetch\_assoc,而不是查询。

答案 2 :(得分:0)

不好的做法,永远不应该在for循环中调用函数,否则会导致性能问题。

for($i =  0 ;  $i <  mysql_num_rows($result) ; $i++){
    $row = mysql_fetch_assoc($result);
    echo($row['a']);
}

你还想在循环中获取关联数组吗?这也会每次都执行?

良好做法

$countRows = mysql_num_rows($result);

for($i=0; $i<$countRows; $i++){
    $row = mysql_fetch_assoc($result);
    echo "Row: ".$row['a']."<br />";
}

$row = mysql_fetch_assoc($result);

foreach($row as $key=>$value) {
   echo "Key: ".$key." Value: ".$value."<br />";
}

while($row = mysql_fetch_assoc($result))
{
   echo "Row: ".$row['a'] . "<br />";
}

答案 3 :(得分:0)

我将回答实际问题(“UNION ALL会返回数组吗?”)。

不,union [all]返回数组,它用于连接结果集。如果在union all表单中使用它,则确保保留结果结果集中的所有重复行。

那就是all