【问题标题】:SQL how to "join" two tablesSQL如何“连接”两个表
【发布时间】:2020-12-09 21:04:50
【问题描述】:

无法想象简单的解决方案。我有两张桌子。
表1(约300行)

id name time
ID1 peter 12:00:00
ID2 alice 12:33:00
ID3 tom 08:00:00

表 2(大约 3'000'000 行)

id time arg1
ID1 12:00:00 23
ID1 11:00:00 34
ID2 12:45:00 21
ID2 12:33:00 22
ID2 08:00:00 12
ID3 08:00:00 21
ID1 08:00:00 23

需要这样的输出表

id name time arg1
ID1 peter 12:00:00 23
ID2 alice 12:33:00 22
ID3 tom 08:00:00 21

【问题讨论】:

  • 请发布您到目前为止所尝试的内容。
  • table2 中的哪一行应该用于table1 中的每一行?例如对于 ID1 (Peter),为什么要使用 time = 12:00, arg1 = 23 而不是 11:00, arg1 = 34
  • 你试过JOIN吗?
  • 表 1 说:彼得在 12:00 做了某事
    表 2 说用户 IDx 在 11:00 做了 34
    并输出我需要“彼得在 12:00 做了什么"

标签: sql join


【解决方案1】:
Select t1.ID, t1.time, t1.name, t2.arg1 from table1 t1
Inner join table2 t2 on t2.id = t1.id
Where t1.time=t2.time

【讨论】:

  • 有效,有效!谢谢你们。 (在我的许多尝试中,我也尝试过这个怪物“选择 P.id, name,time arg1 from (select id, max(time) as time from t2 group by id) P inner join t2 on P.id = t2,id and P.time = t2.time 左外连接 t1 on p.id=t1.id order by name)
猜你喜欢
  • 1970-01-01
  • 2012-02-28
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
相关资源
最近更新 更多