[英]SQL: selecting fields from another table
我是sql的新手,感谢您提供以下帮助:我有2个表:table1包含userID和y1字段,而表2包含userID和三个附加字段:x1,x2,x3和x4对于table1中的每一行,我需要选择如果x1,x2和x3不为null,则来自表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 =蓝色,x2 =圆形和x3 =大的结果
UserID x4
1 11
2 33
最后一行并不完全代表您的意思,但我假设您希望table1中的所有行都加上table2.x4。
您要查询的内容将是这样的:从table1中选择SELECT table1。*,table2.x4。在table1上向左连接table2。不(table2.x3为NULL)
您似乎想要:
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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.