简体   繁体   中英

Left join sql query

I want to get all the data from the users table & the last record associated with him from my connection_history table , it's working only when i don't add at the end of my query

 ORDER BY contributions DESC

( When i add it , i have only the record wich come from users and not the last connection_history record)

My question is : how i can get the entires data ordered by contributions DESC

SELECT * FROM users LEFT JOIN connections_history ch ON users.id = ch.guid
    AND EXISTS (SELECT 1
        FROM   connections_history ch1
            WHERE  ch.guid = ch1.guid
                HAVING Max(ch1.date) = ch.date) 

The order by should not affect the results that are returned. It only changes the ordering. You are probably getting what you want, just in an unexpected order. For instance, your query interface might be returning a fixed number of rows. Changing the order of the rows could make it look like the result set is different.

I will say that I find = to be more intuitive than EXISTS for this purpose:

SELECT *
FROM users u LEFT JOIN
     connections_history ch
     ON u.id = ch.guid AND
        ch.date = (SELECT  Max(ch1.date)
                   FROM connections_history ch1
                   WHERE ch.guid = ch1.guid
                  )
ORDER BY contributions DESC;

The reason is that the = is directly in the ON clause, so it is clear what the relationship between the tables is.

For your casual consideration, a different formatting of the original code. Note in particular the indented AND suggests the clause is part of the LEFT JOIN , which it is.

SELECT * FROM users 
LEFT JOIN connections_history ch ON 
  users.id = ch.guid
  AND EXISTS (SELECT 1
              FROM   connections_history ch1
              WHERE  ch.guid = ch1.guid
              HAVING Max(ch1.date) = ch.date
             ) 

We can use nested queries to first check for max_date for a given user and pass the list of guid to the nested query assuming all the users has at least one record in the connection history table otherwise you could use Left Join instead.

select B.*,X.* from users B JOIN (
select A.* from connection_history A 
where A.guid = B.guid and A.date = (
select max(date) from connection_history where guid = B.guid) )X on 
X.guid = B.guid 
order by B.contributions DESC;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM