我是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列以两个不同的值出现,我假设snipps indexNum栏显示插入的内容,但indexCodes indexNumber显示的结果不同(我相信这是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;
就我个人而言,我更喜欢使用联接语法,这是查看查询的一种更干净的方式。