如何组合以下SQL查询,以便在同一行的3个单独列中获得一个包含州,城市和邮政编码名称的输出表?我对SQL没有什么经验,但是如果我能做一个单独的查询,那对我来说似乎好一点。
SELECT City_tx FROM City WHERE City_id = 11
SELECT StateProv_tx FROM StateProv WHERE StateProv_id = 12
SELECT PostalCode_tx FROM PostalCode WHERE PostalCode_id = 13
答案 0 :(得分:2)
如果表之间没有任何关系。只需声明3个变量&设置它们(只是除上述答案之外的另一种方法);
DECLARE @City VARCHAR(100), @StateProv VARCHAR(100), @PostalCode VARCHAR(100)
SELECT @City = City_tx FROM City WHERE City_id = 11
SELECT @StateProv = StateProv_tx FROM StateProv WHERE StateProv_id = 12
SELECT @PostalCode = PostalCode_tx FROM PostalCode WHERE PostalCode_id = 13
SELECT @City City, @StateProv StateProv, @PostalCode PostalCode
答案 1 :(得分:0)
select max(City_tx),max(StateProv_tx),max(PostalCode_tx) from
(
SELECT City_tx ,'' StateProv_tx, '' PostalCode_tx FROM City WHERE City_id = 11
union all
SELECT '' City_tx ,StateProv_tx, '' PostalCode_tx FROM StateProv WHERE StateProv_id = 12
union all
SELECT '' City_tx ,'' StateProv_tx, PostalCode_tx FROM PostalCode WHERE PostalCode_id = 13
) t
答案 2 :(得分:0)
假设City_id
,StateProv_id
和PostalCode_id
都是唯一的,那么只需使用交叉连接并仅限制这些字段。如果你在其他数据之间没有其他关系,那么可能不是最有效的,但不是任何其他好的选择:
SELECT City_tx, StateProv_tx, PostalCode_tx
FROM City, StateProv, PostalCode
WHERE City_id = 11 AND StateProv_id = 12 AND PostalCode_id = 13
尽管如此,除非我们没有架构或有关数据如何布局的任何信息,否则这可能无法为您工作。
答案 3 :(得分:0)
SELECT City_tx, (SELECT StateProv_tx FROM StateProv WHERE StateProv_id = 12) as sp_tx, (SELECT PostalCode_tx FROM PostalCode WHERE PostalCode_id = 13) as pc_tx FROM City WHERE City_id = 11
它应该有效......至少在MySQL中。
答案 4 :(得分:0)
Cross join
似乎是一种很好的方法,假设在每种情况下只返回一行:
select *
from (SELECT City_tx FROM City WHERE City_id = 11) c cross join
(SELECT StateProv_tx FROM StateProv WHERE StateProv_id = 12) s cross join
(SELECT PostalCode_tx FROM PostalCode WHERE PostalCode_id = 13) p