自然加入MySQL中的两个表

时间:2013-04-02 23:34:43

标签: mysql sql inner-join

在过去的一小时里,我一直在查看这段代码,试图弄清楚我的错误。这可能是显而易见的,但在电脑前这么长时间后,我可能只需要第二眼就可以弹出它。我连接了多个表来保持1NF和2NF,但是有两个人绊倒我。

我有一个名为my_contacts的主表,还有一个名为zip_code的状态/城市信息。 zip_code保存主键行'zip_code',my_contacts保存其外键。

问题是,当我尝试加入它们时,我得到了什么。我搞砸了吗?下面是每个的SHOW CREATE TABLE:

对于my_contacts:

    CREATE TABLE `my_contacts` (
    `contact_id` int(11) NOT NULL AUTO_INCREMENT,
    `last_name` varchar(100) DEFAULT NULL,
    `first_name` varchar(100) DEFAULT NULL,
    `phone` varchar(13) DEFAULT NULL,
    `email` varchar(100) DEFAULT NULL,
    `gender` char(1) DEFAULT NULL,
    `birthday` date DEFAULT NULL,
    `prof_id` int(11) DEFAULT NULL,
    `zip_code` int(11) DEFAULT NULL,
    PRIMARY KEY (`contact_id`),
    KEY `mc_profid_fk` (`prof_id`),
    KEY `my_zip_fk` (`zip_code`),
    CONSTRAINT `mc_profid_fk` FOREIGN KEY (`prof_id`) 
    REFERENCES `profession` (`prof_id`),
    CONSTRAINT `my_zip_fk` FOREIGN KEY (`zip_code`) REFERENCES `zip_code` (`zip_code`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

for zip_code:

    CREATE TABLE `zip_code` (
    `zip_code` int(11) NOT NULL AUTO_INCREMENT,
    `city` varchar(50) DEFAULT NULL,
    `state` char(2) DEFAULT NULL,
    PRIMARY KEY (`zip_code`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

提前致谢。

1 个答案:

答案 0 :(得分:1)

zip_code表中的zip_code设置为auto_increment。

这似乎不是该表中此字段的可能选择。你在哪里存储zip_code?顺便说一句,我希望实际的邮政编码存储为字符串,以处理前导0。邮政编码可能看起来像一个数字,但它实际上不是一个(排序定义不明确,算术运算没有意义)。