0

i am trying to run an SQL Query to select all rows from a table and then display the column with the lowest value for each row.

for example, lets start with row1...

columns1, column2, column3, column4

the lowest value for this row is in column3 so i need to echo the column3 value then on row2, column4 has the lowest value so column4 should be displayed for this row.

i did try this code:

$sql="SELECT * from callplanmeta ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
    $sql2="SELECT *, MIN(NULLIF(".$result["callplanname"].",0)) as number2 from callplandata ";
    echo $sql2;
    $rs2=mysql_query($sql2,$conn) or die(mysql_error());
    while($result2=mysql_fetch_array($rs2))
    {
        echo $result2["description"].' - '.number_format($result2["number2"],2).'<br><br>';
    }
}

however i then realised that it was doing it the wrong way round and only showing the lowest value for 1 row

the column names in the callplandata table match the column callplanname in the callplanmeta table

the columns in the callplandata table are dynamic so they are changing all the time and more are constantly being added

4

3 回答 3

0

您可以通过以下方法解决这个难题:

SELECT

(SELECT columns1 from myTable) as myField

UNION 
(SELECT column2 from myTable)

UNION 
(SELECT column3 from myTable)

order by myField ASC LIMIT 1
于 2013-10-13T16:11:39.100 回答
0

首先你会使用这个

SELECT 
        GROUP_CONCAT(COLUMN_NAME)
FROM 
        INFORMATION_SCHEMA.COLUMNS
WHERE 
        table_name = 'mytable'
AND 
        ORDINAL_POSITION>2

要检索所有列,请将其形成为 PHP 中的字符串,然后运行以下 (col1,col2,col3) 需要替换为您可以使用上一个查询形成的 column_name 字符串。

添加了 PHP 代码

从你的代码中我明白了两件事,首先你不需要一个while循环来处理第一个查询,因为它只会返回一个记录,你需要一个while循环来处理第二个查询,因为它会返回多行,让我试着弥补相应地编码

<?php 

$field_string= $mysqli->query("SELECT GROUP_CONCAT(COLUMN_NAME) AS field_string
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE table_name = `callplandata`
               AND ORDINAL_POSITION>2")->fetch_object()->field_string;

(上面的 >2 意味着这将忽略前两列,在您的情况下似乎是数字、描述。如果您有更多或更少的字段要忽略,那么您可以相应地修改此数字)

然后,您可以将此 field_string 值用于需要找到最少的其他查询

$sql2="SELECT LEAST(".$field_string.") AS number FROM `callplandata`"; 

$rs2=mysql_query($sql2,$conn); 

while($result2=mysql_fetch_array($rs2)) 
{ 
   echo $result2["number"].'<br>'; 
} 
?>

这将为您提供除所有行的前两列之外的所有列中的最低值,并将其显示在屏幕上。我不是PHP程序员,所以只是用PHP编写代码,可能会有小错误。

于 2013-08-19T12:47:19.783 回答
0

你也可以用这个得到结果

SELECT Id, CASE WHEN COLUMN1 <= COLUMN2 and COLUMN1 <= COLUMN3 THEN COLUMN1 WHEN COLUMN2 <= COLUMN1 and COLUMN2 <= COLUMN3 THEN COLUMN2 ELSE COLUMN3 END AS minimum FROM table_name

您可以获得任意数量的列的结果。

于 2013-08-19T13:07:03.873 回答