简体   繁体   中英

Two SELECT SQL statements

I try to get data from db. I can get max min values but I can't get the x and y values listed.

the codes are as follows. Thank you for your help

<?php

$sql = "SELECT  * FROM veri UNION ALL SELECT MAX(x) as 'maxx', MIN(x) as 'minx', MAX(y) as 'maxy', MIN(y) as 'miny' FROM veri  ";
$result = mysql_query($sql);
$result_array = array();
while($row = mysql_fetch_array($result)){
    $result_array[] = $row;

    echo $row['x'];
    echo $row['y'];
    echo $row['miny'];
    echo "<br>";
    echo $row['maxy'];
    echo "<br>";
    echo $row['minx'];
    echo "<br>";
    echo $row['maxx'];
    echo "<br>";
}

?>

I'm not sure I understand your intention with the query, but if veri have two columns your two selects are not union compatible since your first query have two columns and your second query have four columns. A query is union compatible with another query iff they have the same number of columns and the corresponding columns have the same type. Furthermore, the result of a query is a table so you cannot have different names on the columns for different rows (x vs maxx).

You could either use four sub-selects for min and max values:

SELECT x, y, (SELECT MAX(x) FROM veri) as maxx
           , (SELECT MIN(x) FROM veri) as minx
           , (SELECT MAX(y) FROM veri) as maxy
           , (SELECT MIN(y) FROM veri) as miny
FROM veri

or you need a classifier to determine what the row represents:

SELECT 'row' as origin, x, y FROM veri
UNION ALL
SELECT 'max' as origin, max(x) as x, max(y) as y FROM veri
UNION ALL
SELECT 'min' as origin, min(x) as x, min(y) as y FROM veri

However, in this case it probably makes most sense to split it into two queries:

q1: SELECT x, y FROM veri

q2: SELECT MAX(x) as maxx, MIN(x) as minx, MAX(y) as maxy, MIN(y) as miny FROM veri

and handle them individually.

OK I splited the queries into two like you said. It worked out. Thank you

$sql1= "SELECT x,y FROM veri  ";
$result1=mysql_query($sql1) or die(mysql_error());
$result_array = array();
while($row1 = mysql_fetch_array($result1)){
$result_array[] = $row1;

       echo $row1['x'];
       echo $row1['y'];
    }



$sql2= "SELECT  MAX(x) as 'maxx', MIN(x) as 'minx', MAX(y) as 'maxy', MIN(y) as 'miny' FROM veri  ";
$result2=mysql_query($sql2) or die(mysql_error());
$result_array = array();
while($row2 = mysql_fetch_array($result2)){

        echo $row2['miny'];
        echo "<br>";
        echo $row2['maxy'];
        echo "<br>";
        echo $row2['minx'];
        echo "<br>";
        echo $row2['maxx'];
        echo "<br>";

   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM