内部连接在mysql中给出错误代码1052

时间:2015-03-21 20:32:46

标签: mysql

我创建了一个包含以下表格的数据库:

        CREATE SCHEMA IF NOT EXISTS `facturatiedatabase` ;
        USE `facturatiedatabase` ;

        DROP TABLE IF EXISTS tblAddress ;
        DROP TABLE IF EXISTS tblContact ;
        DROP TABLE IF EXISTS tblCustomers ;

        CREATE TABLE tblCustomers  (
        customerID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(30) NOT NULL,
        lastname VARCHAR(30) NOT NULL,
        vat VARCHAR(30) NOT NULL,
        customerVisible varchar(1) NOT NULL DEFAULT 'T'
        ) ENGINE=InnoDB;


        CREATE TABLE tblContact (
        contactID INT NOT NULL  AUTO_INCREMENT PRIMARY KEY,
        email VARCHAR(100),
        phone VARCHAR(100),
        customerID int,
        CONSTRAINT FK_customerID_Contact FOREIGN KEY (customerID) REFERENCES tblCustomers(customerID) 
        ) ENGINE=InnoDB;

        CREATE TABLE tblAddress (
        addressID INT NOT NULL  AUTO_INCREMENT PRIMARY KEY,
        street VARCHAR(100),
        houseNumber VARCHAR(15),
        city VARCHAR (100),
        country VARCHAR (100),
        customerID int,
        CONSTRAINT FK_customerID_Adress FOREIGN KEY (customerID) REFERENCES tblCustomers(customerID)
        ) ENGINE=InnoDB;


        INSERT INTO tblCustomers (firstname, lastname,vat) 
        VALUES ("John","Doe","UV45856855");

        INSERT INTO tblContact (customerID,phone, email) 
        VALUES ((SELECT DISTINCT LAST_INSERT_ID() FROM tblCustomers), "0000001","Johndoe@gmail.com");

        INSERT INTO tblAddress (customerID,street,housenumber,city,country) 
        VALUES ((SELECT DISTINCT LAST_INSERT_ID() FROM tblCustomers), "berkenlaan","1a","Harelbeke","Belgie");

但是当我尝试跟随内部联接时,它会给我以下错误: LIMIT 0,1000错误代码:1052。列' customerID'在字段列表中不明确0.000秒。

        SELECT customerID, firstname, lastname, vat,email
        FROM tblCustomers
        INNER JOIN tblContact on tblCustomers.customerID = tblContact.contactID

1 个答案:

答案 0 :(得分:0)

错误消息说明了一切:列名customerID包含在两个表中。那么mysql应选择哪个值?这是模糊的,因此错误。

尝试使用此变体:

SELECT tblCustomers.customerID AS customerID, firstname, lastname, vat,email
    FROM tblCustomers
    INNER JOIN tblContact on tblCustomers.customerID = tblContact.contactID

(或者如果你需要那个,请选择其他表格的栏目......)

坦率地说,我怀疑你的ON条款是你想要使用的条款。不应该是ON tblCustomers.customerID = tblContact.customerID而是{{1}}吗?