问题描述
我是SQL的新手,我遇到了麻烦。
我有3张桌子:
CREATE TABLE indexCodes
{
(indexNum VARCHAR(5) PRIMARY KEY,courseString VARCHAR(10),title VARCHAR(20)
}
CREATE TABLE user
{
(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,email VARCHAR(255) NOT NULL,password VARCHAR(255) NOT NULL)
}
CREATE TABLE snipes
{
(snipeNumber INT NOT NULL PRIMARY KEY AUTO_INCREMENT),FOREIGN KEY indexNum REFERENCES indexcodes(indexNum),FOREIGN KEY userID REFERENCES user(id)
}
并使用
插入到片段中INSERT INTO snipes(indexNum,userID) VALUES ("06666",1);
INSERT INTO snipes(indexNum,userID) VALUES ("06675",1);
我跑步时
SELECT * FROM snipes,user,indexcodes where id=1
两个indexNum列出现两个不同的值,我假设snipes indexNum列显示插入的内容,但indexCodes indexNum显示不同的结果(我相信这是indexCodes中的前两个条目)
解决方法
如果将所有表放在FROM子句中,并且仅用逗号分隔,而没有将表与WHERE子句联接的任何限制,则可以得到FROM子句中引用的所有表的笛卡尔积,例如,或者使用JOIN语法而不是将所有表都放在FROM子句中。这是两个适用于您的方案的示例:
- WHERE子句
SELECT * FROM snipes s,t_user u,indexcodes i where
s.indexNum = i.indexnum
and s.userid = u.id
and id=1;
- JOIN语法
SELECT * FROM snipes s
inner join t_user u on s.userid = u.id
inner join indexcodes i on s.indexNum = i.indexnum
where id=1;
我个人更喜欢使用连接语法,这是查看查询的一种更简洁的方法。