【问题标题】:Join two tables by matching column values in SQL通过匹配 SQL 中的列值连接两个表
【发布时间】:2015-12-17 21:49:47
【问题描述】:

您好,我一直在尝试通过它们的匹配值来连接两个表。

我有我的第一个表名为 location 的列:(国家、州、城市、纬度、经度)

我有第二个名为 twitter 的表,其中包含以下列:(用户、推文、纬度、经度)

我想要做的是将位置表加入到 Twitter 表中,当纬度和经度匹配时,它将在 Twitter 数据旁边显示相应的国家、州和城市列。

到目前为止,我尝试过没有运气。它所做的就是将每个城市添加到多行中的每条推文中。

select * from twitter
join location 
on twitter.latitude = location.latitude
and twitter.longitude = location.longitude

请帮忙!

【问题讨论】:

  • 您的描述表明两个表中的latitude 值相同,longitude 也是。
  • 嗨,戈登,例如,假设我有一条经纬度为 50 和 100 的推文。在我的坐标列表中,50 和 100 匹配亚利桑那州。如何使表格输出与推文相关的亚利桑那州。
  • 。 .您需要提供样本数据和所需的结果。您的查询看起来正确。

标签: sql hadoop hive


【解决方案1】:

由于我们可能没有每个纬度/经度的位置,我们使用LEFT JOIN

select t.User
    ,t.Tweet
    ,t.Latitude
    ,t.Longitude
    ,l.Country
    ,l.State
    ,l.City
from twitter t
left join location l on t.latitude = l.latitude
    and t.longitude = l.longitude

【讨论】:

    【解决方案2】:

    使用左连接。它会给你所有的结果。

    select * from twitter
    left join location 
    on twitter.latitude = location.latitude
    and twitter.longitude = location.longitude
    

    【讨论】:

      【解决方案3】:
      select * from twitter t
      inner join location l
      on t.latitude = l.latitude
      WHERE t.longitude = l.longitude
      

      【讨论】:

      • 能否请您 edit 解释为什么这段代码回答了这个问题?纯代码答案是discouraged,因为它们不教授解决方案。 (在这种情况下,我有理由确定效果与发布的代码相同。)
      猜你喜欢
      • 2015-01-05
      • 1970-01-01
      • 2020-07-12
      • 2021-11-21
      • 2021-11-19
      • 2015-08-24
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多