I have the following table in my database.
CREATE TABLE `market_messages` (
`pm_id` int(11) NOT NULL,
`pm_item_index` int(11) DEFAULT NULL,
`pm_item_id` varchar(11) COLLATE utf8_polish_ci NOT NULL,
`pm_item_sender` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`pm_item_client` varchar(30) COLLATE utf8_polish_ci NOT NULL,
`pm_item_sender_id` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`pm_item_client_id` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`pm_item_name` varchar(80) COLLATE utf8_polish_ci DEFAULT NULL,
`pm_sender` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`pm_receiver` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`pm_entry_start` timestamp NULL DEFAULT NULL,
`pm_message` text COLLATE utf8_polish_ci DEFAULT NULL,
`pm_index` int(11) DEFAULT NULL,
`pm_type` varchar(10) COLLATE utf8_polish_ci DEFAULT NULL,
`pm_user_offer` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`pm_status` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
Now I'm trying to group messages and order in specific sequence on the list.
I need to list comments based on last entry into m_entry_start
column which type is timestamp.
Here is my query, but result is not good:
$sql = "SELECT *
FROM market_messages
WHERE (pm_item_client = '$user_name'
AND pm_item_client_id = '$user_id')
OR (pm_item_sender = '$user_name'
AND pm_item_sender_id = '$user_id')
GROUP BY pm_item_id, pm_item_client_id, pm_item_sender_id
ORDER BY MAX(pm_entry_start) DESC;";
Result is not this what I have expected.
Echo $fetch['m_entry_start'];
doesn't give me right result.
I'm expecting max value of pm_entry_start
timestamp from each group, but in results is taken probably first value. Additionally `pm_entry_start' is echoed with ago() function to show elapsed time. Ago function is converting timestamp in format 2021-10-01 10:00:19 to something like 3 minutes ago, or 1 day ago etc.
This is example result:
$user_name | ago(timestamp) |
---|---|
Adam | 1 month ago |
Eve | 23 days ago |
Terese | 2 months ago |
Mark | 5 days ago |
Monica | 3 min ago |
I expecting results in order based on timestamp in descending order so from the last entry to the first.
$user_name | ago(timestamp) |
---|---|
Monica | 3 min ago |
Mark | 5 days ago |
Eve | 23 days ago |
Adam | 1 month ago |
Terese | 2 months ago |
How to write the good query? I have started programming in PHP last year. This project is my first with use of MySQL database. Any help appreciated.