【问题标题】:SQL query statement to display same column type with multiple tablesSQL查询语句以显示具有多个表的相同列类型
【发布时间】:2013-02-24 16:08:21
【问题描述】:

我有一个表格视图,它尝试采用两个整数国家代码(起点和目的地)并将这些整数代码替换为实际的两个字母国家代码,同时保持第二个表的映射。

这是两个表的示例

国家代码:

integerCode twoDigitCode   fullName
     0           US      United States
     1           BE        Belgium
     2           CN         China
     ...

区域:

origin destination col3 col4
   0        1       x    y
   0        2       z    a
   1        2       u    b
   2        0       x    x
   2        1       i    f
   ...

我想做的是在视图中得到这样的结果:

origin destination col3 col4
  US        BE       x   y
  US        CN       z   a
  ...

我已经尝试了几个不同的 SQL 查询,像这样

SELECT twoDigitCode as origin, twoDigitCode as destination
FROM country INNER JOIN Zone ON zone.destination = country.twoDigitCode 
WHERE zone.origin = country.twoDigitCode 

但它似乎只是不断重复两次查找的结果。

我的第一个问题是我什至可以用 SQL 查询做我想做的事情吗?第二个是有一个很好的例子或网站可以解释我如何获得这样的结果。

任何帮助将不胜感激。

【问题讨论】:

    标签: sql select sql-view


    【解决方案1】:

    您需要为 2 个查找列中的每一个加入国家代码表:

    SELECT co.twoDigitCode as origin, cd.twoDigitCode as destination, z.col3, z.col4
    FROM zones z
    INNER JOIN country co ON country.integerCode = z.origin
    INNER JOIN country cd ON country.integerCode = z.destination
    

    [注意:如果 origindestination 列可以为空,您将使用左连接而不是内连接]

    【讨论】:

    • 成功了。 oldDHLRates 是我正在工作的表的临时表名称。我更新了问题陈述以免混淆其他人。所以我只是错过了一个加入?我以为我试过了,但我想我错过了:)。感谢您的快速回答!
    【解决方案2】:

    您只需要两个单独的 JOIN:

    SELECT c1.twoDigitCode origin, c2.twoDigitCode destination, z.col3, z.col4
    FROM Zones z
    JOIN Country c1 ON c1.integer.code=z.origin
    JOIN Country c2 ON c2.integer.code=z.destination
    

    【讨论】:

      【解决方案3】:

      好的,您正在尝试创建一个查询,该查询将通过将每个 origindestination 组件替换为其对应的两位国家代码来“填充”Zones 表中的每条记录。换句话说,您正在解码源数据和目标数据。您可以对 Zones 表执行两次 Join:一次填写起点,第二次填写终点。

      您可以将其分解为两个查询:

      1. 通过将 Zones 表与 Country Codes 表连接起来来解码来源。 例如

        SELECT *
        FROM Zones, Country Codes
        WHERE origin = integerCode
        

        这将创建一个临时表,其中每行包含以下列:

        (origin, destination, col3, col4, integerCode, twoDigitCode, fullName)

      2. 使用相同的过程解码目标。也就是说,再次将第 1 步创建的表与 Country Codes 表连接起来,但这次 WHERE 子句应将目标与 integerCode 匹配。

      免责声明:我是学生,不是专家。我不声称我的解决方案的效率、准确性或正确性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-31
        • 1970-01-01
        • 2016-05-21
        • 1970-01-01
        • 2022-01-09
        • 2019-10-07
        • 2013-11-19
        • 2013-12-09
        相关资源
        最近更新 更多