MySQL JOIN Multiple Tables With LIMIT Last Table By DateTime per result

限于喜欢 提交于 2019-12-24 16:57:14

问题


I got an interesting one. I have 3 tables I am joining. The last table I joined, I want to only see the latest entry by date and not double up my results with the same user and just have different login times.

Example (this is a sample table only):

    SELECT a.user_id
       a.user_name,
       b.department,
       c.last_logon_date_time,
       c.computer_name
 FROM table1 a
 LEFT OUTER JOIN table2 b ON a.user_id = b.user_id
 LEFT OUTER JOIN table3 c ON c.user_id = c.user_id

Below will give me the results I am looking for but looks very inefficient and is really slow. Any way of speeding this up and making it more efficent?

I could do this

         SELECT a.user_id
       a.user_name,
       b.department,
       (SELECT c.last_logon_datetime FROM table 3 c WHERE a.user_id = c.user_id ORDER BY c.last_logon_datetime DESC LIMIT 1) as last_logon_datetime,
       (SELECT c.computer_name FROM table 3 c WHERE a.user_id = c.user_id ORDER BY c.last_logon_datetime DESC LIMIT 1) as  computer_name
 FROM table1 a
 LEFT OUTER JOIN table2 b ON a.user_id = b.user_id

Thank You.


回答1:


You can JOIN to a "table" created from a subselect like this:

SELECT t1.user_id, t1.user_name, t2.department, t3.computer_name, t3.logon_date
FROM table1 AS t1
LEFT OUTER JOIN table2 AS t2 ON t1.user_id = t2.user_id
LEFT OUTER JOIN
(SELECT user_id, computer_name, MAX(last_logon_date) AS `logon_date` FROM table 3 GROUP BY computer_name) AS t3 ON t1.user_id = t3.user_id


来源:https://stackoverflow.com/questions/14615876/mysql-join-multiple-tables-with-limit-last-table-by-datetime-per-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!