问题
I am working on dating website with php and mysql as backend. I've two tables. First table is user table where all user info will be stored and other table is visituser table where if one user view another users profile then there will be an entry in visituser table. Every time if one user visits another users profile then there will be an entry in visituser table. There will be multiple entry for one user visit to another user. My problem is that i've to show the visitor one time with latest visit date. My query is given below =>
SELECT
a.*, b.onlinestatus,
b.username,
b.age
FROM
tbl_visitprofile a
LEFT JOIN tbl_user b ON a.visitorid = b.id
WHERE
b. STATUS != '2'
AND a.visitmemberid = '10'
AND a.visitorid NOT IN (
SELECT
user_id
FROM
tbl_pauseusers
)
AND a.blockstatus = '0'
GROUP BY
a.visitorid
ORDER BY
a.id DESC
LIMIT 0,
12
If i am not using the group by in this query then i am getting the latest visit entry but if i am using group by then i am not getting the latest visit entry. I'd searched alot but didn't find my annswer anywhere. Any help will be appreciated. Thanks in advance
回答1:
You can achieve this using the MAX
group function. I have cleaned up the query a bit but fundamentally this should retain the same logic you had before whilst being slightly more optimisable. Just change a.date_time for whatever the date time field is in your table.
SELECT
a.visitorid,
MAX( a.date_time ) AS last_visit_date_time,
b.onlinestatus,
b.username,
b.age,
FROM tbl_visitprofile a
INNER JOIN tbl_user b
ON b.id = a.visitorid
AND b.STATUS != '2'
LEFT JOIN tbl_pauseusers p
ON p.user_id = a.visitorid
WHERE a.visitmemberid = '10'
AND a.blockstatus = '0'
AND p.user_id IS NULL
GROUP BY a.visitorid
ORDER BY last_visit_date_time DESC
LIMIT 0 , 12;
This will order the records by the date/time of last visit and return the latest 12.
来源:https://stackoverflow.com/questions/41547252/group-by-and-order-by-in-mysql-query