SQL:选择表并包含另一个表中的字段/值
我想完成的是从一个表中选择不同的值,并包含一个字段值,该字段值将从另一个表的另一个表中选择 以下是我声明的一个例子:SQL:选择表并包含另一个表中的字段/值,sql,join,subquery,inner-join,Sql,Join,Subquery,Inner Join,我想完成的是从一个表中选择不同的值,并包含一个字段值,该字段值将从另一个表的另一个表中选择 以下是我声明的一个例子: SELECT table1.Foo, <- ID table1.Bar, <- some value (SELECT table2.Baz from table2 <- another value I'd like to select from another table WHERE table1.Foo = tabl
SELECT table1.Foo, <- ID
table1.Bar, <- some value
(SELECT table2.Baz from table2 <- another value I'd like to select from another table
WHERE table1.Foo = table2.Foo and table2.Qux = 'A') As value1
FROM table1
INNER JOIN table2 ON table1.Foo = table2.Foo
WHERE table1.Bar = '2'
表2
|---------------------|------------------|------------------|
| Foo | Baz | Qux |
|---------------------|------------------|------------------|
| 1 | 100 | A |
|---------------------|------------------|------------------|
| 1 | 200 | B |
|---------------------|------------------|------------------|
| 2 | 150 | A |
|---------------------|------------------|------------------|
| 2 | 175 | B |
|---------------------|------------------|------------------|
结果尝试此查询:
SELECT
t1.Foo,
t1.Bar,
t2.Baz AS value1
FROM table1 t1
INNER JOIN table2 t2
ON t1.Foo = t2.Foo
WHERE
t2.Qux = 'A';
您可以使用SELECT DISTINCT语句 选择不同的table1.Foo, 表1.酒吧, 从表2中选择表2.Baz 其中table1.Foo=table2.Foo,table2.Qux='A'作为值1 来自表1 内连接表2 其中table1.Foo=table2.Foo和table1.Bar='2'如果使用子查询,则无需再次执行联接: 如果不支持,请使用LIMIT子句代替TOP 您可以将LIMIT子句实现为
select *,
(select Baz
from table2
where Foo = t1.Foo and
Qux = 'A'
order by Baz -- Use DESC if necessary
LIMIT 1) as value1
from table1 t1;
添加一些示例表数据和预期结果。作为格式化文本,而不是图像。如果子查询将返回多个记录,那么您选择单个值的逻辑是什么?您是说我有一个返回多个值的查询,如何使其仅返回一个值?那么,你需要具体说明如何进行的逻辑;您想要最小值、最大值、平均值、按时间戳列排序时的第一个值,还是其他逻辑?最好的建议是给出一个完全可证明的例子;包含所需结果的示例数据,表示要应用的规则。这可能有助于您阅读以下内容:我想获取table2.Baz值,该值与table1中的记录具有相同的ID Foo,其中table2.Qux='A'@Frame我更新了我的答案,但是,如果table1记录与多个table2记录匹配,则示例数据无法显示发生的逻辑。对于table2中的每个ID,在Qux中有3个值包含“a”、“B”或“C”。因此,如果我添加table2.Qux='A',结果应该只有一条记录um…我的查询已经做到了这一点。你试过运行它了吗?你的解决方案似乎有效我还没有完全检查结果。我不明白的是,我似乎找不到显示子查询的方法,这就是为什么在使用subquery@Frame然后在你的问题中解释为什么你希望只有一个记录。这只是您应该始终在代码中给出问题的另一个原因,其中包括DDL,其中包括有关数据的某些约束/假设。
SELECT
t1.Foo,
t1.Bar,
t2.Baz AS value1
FROM table1 t1
INNER JOIN table2 t2
ON t1.Foo = t2.Foo
WHERE
t2.Qux = 'A';
select *,
(select top 1 Baz from table2 where Foo = t1.Foo and Qux = 'A') as value1
from table1 t1;
select *,
(select Baz
from table2
where Foo = t1.Foo and
Qux = 'A'
order by Baz -- Use DESC if necessary
LIMIT 1) as value1
from table1 t1;