MSSQL选择更多表到INSERT

时间:2015-02-05 08:32:54

标签: sql sql-server insert

我正在努力解决这段代码:

INSERT INTO Bier(Bier, BrowuerID, TypeID, GistingID, KleurID, Alcohol)
SELECT bb.Naam, b.BrouwerID, t.TypeID, g.GistingID, k.KleurID, bb.Alcoholperc
FROM BELGISCHBIER AS bb JOIN Brouwer AS b JOIN Type AS t JOIN Gisting AS g JOIN Kleur AS k

有人能说出为什么这不起作用,因为我对SQL

的了解并不多

感谢。

4 个答案:

答案 0 :(得分:1)

您已使用JOINS而没有强制ON子句,该子句确定表格应加入哪些列:

INSERT INTO bier 
            ( 
                        bier, 
                        browuerid, 
                        typeid, 
                        gistingid, 
                        kleurid, 
                        alcohol 
            ) 
SELECT bb.naam, 
       b.brouwerid, 
       t.typeid, 
       g.gistingid, 
       k.kleurid, 
       bb.alcoholperc 
FROM   belgischbier AS bb 
JOIN   brouwer      AS b 
    ON bb.browuerid= b.browuerid
JOIN   type         AS t 
    ON b.BrouwerTypeID = t.BrouwerTypeID
JOIN   gisting      AS g 
    ON bb.GistingID = g.GistingID
JOIN   kleur        AS k
    ON g.KleurID = k.KleurID  

答案 1 :(得分:0)

JOIN,SQL了解INNER JOIN。因此强制使用ON子句。

只有当您使用CROSS JOIN时,您才能写下ON条款。

因此,在ON命令中添加JOIN子句。

答案 2 :(得分:0)

您的代码有一些语法错误,您错过了On子句中的Join操作

尝试这样的想法,

INSERT INTO Bier(Bier, BrowuerID, TypeID, GistingID, KleurID, Alcohol)
SELECT bb.Naam, b.BrouwerID, t.TypeID, g.GistingID, k.KleurID, bb.Alcoholperc
FROM BELGISCHBIER AS bb <on Clause>JOIN Brouwer  AS b  <on Clause> JOIN Type on  AS t <on Clause> JOIN Gisting AS g  <on Clause>  JOIN  Kleur AS k  <on Clause>

或者只是你可以使用交叉连接,它不需要On子句。

语法:

SELECT * 
FROM table1 
CROSS JOIN table2;

示例:

INSERT INTO Bier
            (Bier,BrowuerID,TypeID,GistingID,
             KleurID,Alcohol)
SELECT bb.Naam,b.BrouwerID,t.TypeID,g.GistingID,
       k.KleurID,bb.Alcoholperc
FROM   BELGISCHBIER AS bb
       CROSS JOIN Brouwer AS b
       CROSS JOIN Type AS t
       CROSS JOIN Gisting AS g
       CROSS JOIN Kleur AS k 

答案 3 :(得分:0)

如果您在表格之间没有公共列,请使用其他人提到的Cross Join其他人,您需要使用ON条件加入两个表格

INSERT INTO Bier
            (Bier,BrowuerID,TypeID,GistingID,
             KleurID,Alcohol)
SELECT bb.Naam,b.BrouwerID,t.TypeID,g.GistingID,
       k.KleurID,bb.Alcoholperc
FROM   BELGISCHBIER AS bb
       CROSS JOIN Brouwer AS b
       CROSS JOIN Type AS t
       CROSS JOIN Gisting AS g
       CROSS JOIN Kleur AS k