小编典典

尝试在SQL中使用表别名

sql

我是一名图形设计师,尽我所能来理解表别名,但是它不起作用。这是我到目前为止的内容:

SELECT colours.colourid                  AS colourid1,
       combinations.manufacturercolourid AS colourmanid1,
       colours.colourname                AS colourname1,
       colours.colourhex                 AS colourhex1,
       combinations.qecolourid2          AS colouridqe2,
       colours.colourid                  AS colourid2,
       colours.colourname                AS colourname2,
       colours.colourhex                 AS colourhex2,
       colours.colourid                  AS colourid3,
       combinations.qecolourid3          AS colouridqe3,
       colours.colourname                AS colourname3,
       colours.colourhex                 AS colourhex3,
       colours.colourid                  AS colourid4,
       combinations.qecolourid4          AS colouridqe4,
       colours.colourname                AS colourname4,
       colours.colourhex                 AS colourhex4,
       combinations.coloursupplierid
FROM   combinations
       INNER JOIN colours
         ON colours.colourid = combinations.manufacturercolourid;

现在,想法是在颜色查找表中,id将从查找表中提取颜色代码,十六进制和名称,以便我可以提取要查找的4种颜色的颜色代码,十六进制和名称。我可以使用它,但是它只会产生名字,代码和十六进制,而我只是看不到我做错了什么。


阅读 174

收藏
2021-05-16

共1个答案

小编典典

您的问题是您只链接了colors表中的单个记录,因为您的SQL中只有一个JOIN。该记录将与Manufacturer_colour_id指定的颜色匹配。

您可能还会遇到另一个问题,即您的组合表似乎没有采用正确的标准格式(尽管我可能是错的,因为您不知道要表示的数据的实际性质)。

如果我正确理解了您的问题,那么解决方案(使用您当前的表结构)将更像是:

SELECT C1.colourid              AS colourid1,
   CMB.manufacturercolourid     AS colourmanid1,
   C1.colourname                AS colourname1,
   C1.colourhex                 AS colourhex1,
   CMB.qecolourid2              AS colouridqe2,
   C2.colourid                  AS colourid2,
   C2.colourname                AS colourname2,
   C2.colourhex                 AS colourhex2,
   C3.colourid                  AS colourid3,
   CMB.qecolourid3              AS colouridqe3,
   C3.colourname                AS colourname3,
   C3.colourhex                 AS colourhex3,
   C4.colourid                  AS colourid4,
   CMB.qecolourid4              AS colouridqe4,
   C4.colourname                AS colourname4,
   C4.colourhex                 AS colourhex4,
   CMB.coloursupplierid
FROM   combinations CMB
   LEFT OUTER JOIN colours C1
     ON C1.colourid = CMB.manufacturercolourid
   LEFT OUTER JOIN colours C2
     ON C2.colourid = CMB.qecolourid2
   LEFT OUTER JOIN colours C3
     ON C3.colourid = CMB.qecolourid3
   LEFT OUTER JOIN colours C4
     ON C4.colourid = CMB.qecolourid4

这里发生的是,我将颜色表链接了四次,对于组合表中的每个colour_id字段一次。为此,我每次都需要对表名使用别名,以便我知道在返回的列的列表中使用四种可能的颜色实例中的哪一种。另外,如果一个或多个colour_id列可能为空,我将使用OUTER
JOIN。如果使用INNER JOINs发生这种情况,则整个行将从结果集中删除。

2021-05-16