使用php在sql中找到包含最新条目的列

时间:2016-05-03 08:27:09

标签: php mysql sql database

使用php代码,如果我对id 2感兴趣,我想知道最新条目在哪一列。然后列' time4'随着时间的推移" 2016-03-01 10:01:01"是最新的条目。

id      time1                   time2                   time3                   time4
1       2016-01-01 09:27:24     2016-01-02 10:01:01     2016-01-02 17:05:07     2016-01-01 10:01:01
2       2016-01-02 09:27:24     2016-01-03 10:01:01     2016-02-02 17:05:07     2016-03-01 10:01:01
3       2016-01-02 10:27:24     2016-01-03 11:01:01     2016-02-02 18:05:07     2016-03-01 11:01:01

我试过这个

<?php
$User=1;
$result = $con->query("SELECT MAX(TimeToSelect) as Output
FROM (
    SELECT time1 as TimeToSelect,id
    FROM tableTime
    union
    SELECT time2,id
    FROM tableTime
    union
    SELECT time3,id
    FROM tableTime
        union
    SELECT time4,id
    FROM tableTime
    ) as A
  WHERE id = '$User'");
$row = $result->fetch_array(MYSQLI_BOTH);

echo $something=$row[0];
?>

然后它回应了约会日期&#34; 2016-03-01 10:01:01&#34;而不是列名&#34; time4&#34;。

1 个答案:

答案 0 :(得分:0)

如果您只包含4个要比较的列,则可以使用以下SQL获取所需内容。
您可以更改在特定情况下输入最新时间的条件中的ID&#39; id&#39;。 (每次id)

SELECT MAX(TimeToSelect) as Output
FROM (
    SELECT time1 as TimeToSelect,id
    FROM tableTime
    union
    SELECT time2,id
    FROM tableTime
    union
    SELECT time3,id
    FROM tableTime
    union
    SELECT time4,id
    FROM tableTime
    ) as A
  WHERE id = 1

如果您想获取列名称,请尝试以下SQL:

SELECT ColumnName
FROM (
    SELECT time1 AS TimeToSelect,id,'time1' AS ColumnName
    FROM tableTime
    UNION
    SELECT time2,id,'time2'
    FROM tableTime
    UNION
    SELECT time3,id,'time3'
    FROM tableTime
    UNION
    SELECT time4,id,'time4' 
    FROM tableTime
    ) AS A 
WHERE id = 1 
AND TimeToSelect = (SELECT MAX(TimeToSelect)
                    FROM (
                         SELECT time1 AS TimeToSelect,id,'time1' AS ColumnName
                         FROM tableTime
                         UNION
                         SELECT time2,id,'time2'
                         FROM tableTime
                         UNION
                         SELECT time3,id,'time3'
                         FROM tableTime
                         UNION
                         SELECT time4,id,'time4' 
                         FROM tableTime
                         ) AS A
                    WHERE id = 1
                    )