【问题标题】:Join query with condition by second table通过第二个表加入条件查询
【发布时间】:2020-04-12 13:07:07
【问题描述】:

我有 2 个表,一个是用户,第二个是位置 位置与用户是一对多的关系。 我想根据条件距离(km)> 0.01 的最新位置列出所有用户。请问有人吗?

我尝试了 .syntax 错误(查询 1 错误:'where 子句'中的未知列 'd')

SELECT *, (SELECT distance 
           from locations 
           where locations.user_id = users.id 
           order by created_at DESC 
           LIMIT 1
          ) as d 
from users 
where d > 0.01

编辑

表格 - 用户 - 位置(多个)(id、user_id、lat、lng、距离、created_at)

预期结果 - 最新位置包含的距离小于 0.1(双倍距离)的用户列表(不重复)

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。距离是如何计算的?
  • @Gordon Linoff 插入时自动计算距离。在双
  • 我们应该猜吗? MySQL 不返回简洁的“语法错误”。返回的错误通常有一个有用的提示,错误编号在 MySQL 文档中描述。
  • 是,查询 1 错误:'where 子句'中的未知列 'd'

标签: mysql sql


【解决方案1】:

WHERE 子句中不允许派生列 d,但您可以使用 HAVING 子句:

having d > 0.01

如果不能使用窗口函数,另一种获得所需结果的方法是将表连接到使用NOT EXISTS 返回所需位置的查询:

select u.*, t.distance
from users u inner join ( 
  select l.* from locations l
  where not exists (select 1 from locations where user_id = l.user_id and created_at > l.created_at)
    and l.distance > 0.01 
) t on t.user_id = u.id

【讨论】:

    【解决方案2】:

    您可以使用窗口功能:

    select t.*
    from (select u.*, l.*,
                 row_number() over (partition by u.id order by l.created_at desc) as seq
          from users u inner join
               locations l
               on l.user_id = u.id
         ) t
    where seq = 1 and distance > 0.01;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      相关资源
      最近更新 更多