简体   繁体   English

基于INNER JOIN的SELECT列的INSERT INTO不返回SELECT值

[英]INSERT INTO based on a INNER JOIN'd SELECT column not returning SELECT value

I'm attempting to do an INSERT into Accounts based upon a CustNo value, with the tables connected by AccountId . 我正在尝试根据CustNo值对Accounts进行INSERT插入,并通过AccountId连接表。 For some reason I cannot figure out, the SELECT cust.CustNo column, based on the Custs table columns of GivenName and Surname , is not grabbing anything despite working by the same WHERE clause when tested on it's own. 出于某种原因,我无法弄清楚,尽管自己测试了相同的WHERE子句,但基于GivenNameSurnameCusts表列的SELECT cust.CustNo列却无法捕获任何内容。

INSERT INTO Accounts (Type, Balance, CustNo)
    SELECT 
        'Chequing', 0, cust.CustNo
    FROM 
        Custs cust
    INNER JOIN 
        Accounts ON cust.CustNo = Accounts.CustNo
    WHERE 
        cust.GivenName = 'FirstName' AND cust.Surname = 'LastName';

I can't think of any reason why this is not returning any errors, yet also works and grabs the correct CustNo as a separate SELECT with this same WHERE . 我想不出为什么它不返回任何错误,但也可以用相同的WHERE作为单独的SELECT获取正确的CustNo ,因此无法想到。 Am I missing an essential field somewhere to relate these two tables, or possibly incorrectly joining them? 我是否在某个地方缺少一个重要字段来关联这两个表,或者可能不正确地将它们联接在一起?

While I did not quite end up answering my original question, I DID however find another way to accomplish what I was trying to do with a nested SELECT instead of an INNER JOIN . 虽然我还没有完全回答我的原始问题,但是我还是找到了另一种方法来完成我尝试使用嵌套SELECT而不是INNER JOIN

For anyone else that comes by trying to INSERT data to one table based upon a field (My Name , Surname , and CustNo problem) that is in another related table, try something like this: 对于试图通过将数据INSERT另一个相关表中的字段(“我的Name ,“ Surname ”和“ CustNo问题) INSERT到一个表中的其他任何人,请尝试如下操作:

INSERT INTO Accounts (Type, Balance, CustNo)
SELECT 'Chequing', 0, (SELECT CustNo FROM Custs)//This is the solution, a nested Select
WHERE GivenName = 'FirtName' AND Surname = 'LastName');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM