0

如何组合以下 SQL 查询,以便在同一行的 3 个单独列中获得一个包含州、城市和邮政编码名称的输出表?我对 SQL 几乎没有经验,但是如果我可以只做一个单独的查询,那么做 3 个单独的查询对我来说似乎更好一些。

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
4

5 回答 5

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
于 2012-12-05T19:50:07.380 回答
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
于 2012-12-05T19:44:14.217 回答
0

假设City_id和都是唯一的StateProv_idPostalCode_id那么只需使用交叉连接并且仅限制这些字段。如果您在其余数据之间没有其他关系,可能不是最有效的,但实际上不是任何其他好的选择:

SELECT City_tx, StateProv_tx, PostalCode_tx
FROM City, StateProv, PostalCode
WHERE City_id = 11 AND StateProv_id = 12 AND PostalCode_id = 13

尽管如此,除非我们没有架构或任何有关数据布局方式的信息,否则这甚至可能无法为您工作。

于 2012-12-05T19:49:26.463 回答
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 中。

于 2012-12-05T19:54:33.097 回答
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
于 2012-12-05T20:29:54.327 回答