PostgreSQL 14如何为查询结果添加对应stock列(支持多值)
问题描述
我在PostgreSQL 14中运行以下查询:
select * from tb1 where id in (select id from tb2 where stock = 1313)
查询正常执行,返回结果:
id speed doors 12 100 23
现在希望在结果中新增stock列,得到如下输出:
stock id speed doors 1313 12 100 23
但tb1表中没有stock列,同时需要支持传入多个stock值,比如执行:
select * from tb1 where id in (select id from tb2 where stock in (1313,2324,1234))
能得到:
stock id speed doors 1313 12 100 23 2324 15 150 23 1234 11 100 44
如何实现?
解决方案
不要用IN子查询,改用JOIN关联两张表,这样就能直接获取tb2中的stock列,同时满足每个stock对应一条记录的需求。
单stock值场景
select tb2.stock, tb1.id, tb1.speed, tb1.doors from tb1 join tb2 on tb1.id = tb2.id where tb2.stock = 1313;
多stock值场景
直接修改WHERE条件为IN即可,结果会自动匹配对应的stock值:
select tb2.stock, tb1.id, tb1.speed, tb1.doors from tb1 join tb2 on tb1.id = tb2.id where tb2.stock in (1313,2324,1234);
补充说明
如果tb2中存在同一个id对应多个stock的情况,且你需要确保每个stock只返回一条记录,可以添加DISTINCT去重:
select distinct tb2.stock, tb1.id, tb1.speed, tb1.doors from tb1 join tb2 on tb1.id = tb2.id where tb2.stock in (1313,2324,1234);
内容的提问来源于stack exchange,提问作者datashout
相关产品推荐
相关产品推荐

