Using a php code, I want to know in what column the latest entry is located if I for instance is interested in id 2. Then column 'time4' with the time "2016-03-01 10:01:01" is the newest entry.
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
I tried this
<?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];
?>
But then it echoes the date "2016-03-01 10:01:01" and not the column name "time4".
If you are only contains 4 columns to compare, you can use the below SQL to get what you want.
You can change the id in where condition to get the latest time is entered for particular 'id'. (Each time each 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
If you want to get the columns name, try below 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
)
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.