【问题标题】:SQL: selecting fields from another tableSQL:从另一个表中选择字段
【发布时间】:2018-04-01 19:50:06
【问题描述】:

我是 sql 新手,感谢以下方面的帮助: 我有 2 个表:table1 包含 userID 和字段 y1,而表 2 包含 userID 和三个附加字段:x1、x2、x3 和 x4 对于 table1 中的每一行,如果 x1、x2 和 x3 不为空,我需要从表 2 中选择 x4。 UserID 可以在 table1 或 table2 中出现多次,重要的是我需要结果列行与 table1 中的一样。 谢谢

这是一个例子:

表 1:

UserID y1
1            long
2            short

表 2:

UserID x1 x2 x3 x4
1            blue round big 11
1            blue square big 22
2            blue round   big 33
3            red square  small 77

x1=blue、x2=round 和 x3=big 的结果

UserID  x4
1            11
2            33

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。澄清也是有帮助的。这应该是什么意思:“我需要结果列行与 table1 中的一样”?
  • 刚刚在我的问题中添加了一个示例谢谢

标签: mysql sql


【解决方案1】:

并不完全理解你最后一行的意思,但我假设你想要 table1 中的所有行加上 table2.x4。

您的查询将是这样的: SELECT table1.*, table2.x4 from table1 LEFT OUTER JOIN table2 ON table1.UserID = table2.UserID AND NOT (table2.x1 IS NULL) AND NOT (table2.x2 IS NULL) NOT (table2.x3 IS NULL)

【讨论】:

    【解决方案2】:

    你似乎想要:

    select t1.*, t2.x4
    from table1 t1 join
         table2 t2
         on t1.userid = t2.userid
    where t2.x1 = 'blue' and t2.x2 = 'round' and t2.x3 = 'big';
    

    【讨论】:

      猜你喜欢
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 2015-09-23
      • 2015-08-24
      • 1970-01-01
      相关资源
      最近更新 更多