开发者

Does UNION ALL return an array?

开发者 https://www.devze.com 2022-12-09 02:36 出处:网络
I have a sql statement that is a union of several queries. \"SELECT a, b, c, \'d\' as type FROM x WHERE id = $id UNI开发者_JAVA百科ON ALL

I have a sql statement that is a union of several queries.

"SELECT a, b, c, 'd' as type FROM x WHERE id = $id UNI开发者_JAVA百科ON 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";

I try to iterate through the results and get 'a' value for each row but can't make it to work.

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

I know it is a silly question but I got stuck. Any ideas please? Thanks!


Solved. I changed the query to this and it worked:

"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";


Bad practice, Should never call a function in a for loop this will cause performance issues.

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

Also do you want to fetch the associate array in the loop? this will execute every time as well?

Good Practice

$countRows = mysql_num_rows($result);

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

or

$row = mysql_fetch_assoc($result);

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

or

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


I am going to answer the actual question ("Does UNION ALL return an array?").

No, union [all] doesn't return arrays, it is used to concatenate resultsets. If it is used in the union all form, it makes sure, that all the duplicate rows in the resulting resultset are preserved.

That's all there is to it.


Did you copy/paste your code or retype it?

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

Come to think of it, you should be calling mysql\_fetch\_assoc on a result handle, not a query.

0

精彩评论

暂无评论...
验证码 换一张
取 消