简体   繁体   English

左联接SQL查询

[英]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 我想从用户表中获取所有数据,并从我的connection_history表中获取与他相关联的最后一条记录,仅当我在查询末尾未添加时,该表才有效

 ORDER BY contributions DESC

( When i add it , i have only the record wich come from users and not the last connection_history record) (当我添加它时,我只有来自用户的记录,而没有最后一个connection_history记录)

My question is : how i can get the entires data ordered by contributions DESC 我的问题是:我怎样才能得到按捐款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. order by不应影响返回的结果。 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: 我会说,出于这个目的,我发现=EXISTS更直观:

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. 原因是=直接位于ON子句中,因此很清楚表之间的关系是什么。

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. 特别注意,缩进的AND表示该子句是LEFT JOIN一部分。

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. 我们可以使用嵌套查询来首先检查给定用户的max_date,然后将guid列表传递给嵌套查询,假设所有用户在连接历史记录表中至少有一条记录,否则可以使用Left Join。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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