我确信我可能会犯小错误,但我无法发现错误。我无法理解为什么我无法在MySQL中使用连接查询。
我在DB中有三个关系表:
代码是:
CREATE TABLE IF NOT EXISTS `class` (
`ClassID` INT(11) NOT NULL AUTO_INCREMENT ,
`Class` VARCHAR(500) NULL DEFAULT NULL ,
`Section` VARCHAR(500) NULL DEFAULT NULL ,
PRIMARY KEY (`ClassID`))
ENGINE = InnoDB
AUTO_INCREMENT = 15
DEFAULT CHARACTER SET = utf8;
INSERT INTO `class`(`ClassID`, `Class`, `Section`) VALUES ('1','1','A'), ('2','1','B'), ('3','1','C'), ('4','1','D') ;
CREATE TABLE IF NOT EXISTS `Subject` (
`SubjectID` INT(11) NOT NULL AUTO_INCREMENT ,
`Subject` VARCHAR(45) NULL,
PRIMARY KEY (`SubjectID`))
ENGINE = InnoDB
AUTO_INCREMENT = 53
DEFAULT CHARACTER SET = utf8;
INSERT INTO `Subject`(`SubjectID`, `Subject`) VALUES ('1','English'),('2','Hindi'),('3','Maths'),('4','Science'),('5','Social Science'),('6','Sports'),('7','Physics'), ('8','Chemistry'), ('9','Statistics'), ('10','Computers');
和...
CREATE TABLE IF NOT EXISTS `class_subject` (
ClassID INT (11) NOT NULL,
SubjectID INT (11) NOT NULL,
PRIMARY KEY (ClassID, SubjectID),
INDEX `subject_order_idx` (`ClassID` ASC) ,
CONSTRAINT `class_subject`
FOREIGN KEY (`ClassID` )
REFERENCES `class` (`ClassID` )ON UPDATE CASCADE,
FOREIGN KEY (`SubjectID` )
REFERENCES `subject` (`SubjectID` )ON UPDATE CASCADE)
ENGINE = InnoDB
AUTO_INCREMENT = 15
DEFAULT CHARACTER SET = utf8;
INSERT INTO `class_subject`(`ClassID`, `SubjectID`) VALUES ('1','1'), ('1','2'), ('1','3'), ('12','4'), ('12','5'), ('12','6');
加入查询:
$ClassID = "1";
$sql = "SELECT subject.SubjectID, subject.Subject FROM subject " .
"LEFT JOIN class_subject" .
"ON subject.SubjectID = class_subject.SubjectID " .
"WHERE class_subject.ClassID = $ClassID " .
"ORDER BY SubjectID ASC";
虽然同样的查询在phpMyAdmin中正常工作。
答案 0 :(得分:7)
此字符串末尾需要一个空格:
"LEFT JOIN class_subject " .
如果你完成echo $sql
,你会看到它说:
LEFT JOIN class_subjectON
这样的错误就是为什么我不建议你写那样的字符串。只需在其中写入带换行符的字符串:
$sql = "SELECT subject.SubjectID, subject.Subject FROM subject
LEFT JOIN class_subject
ON subject.SubjectID = class_subject.SubjectID
WHERE class_subject.ClassID = $ClassID
ORDER BY SubjectID ASC";
PHP允许字符串文字中的换行符,SQL也是如此,因此不需要连接。
答案 1 :(得分:3)
第二行末尾需要一个空格:
$sql = "SELECT subject.SubjectID, subject.Subject FROM subject " .
"LEFT JOIN class_subject " .
--------------------------------^
"ON subject.SubjectID = class_subject.SubjectID " .
"WHERE class_subject.ClassID = $ClassID " .
"ORDER BY SubjectID ASC";
答案 2 :(得分:1)
@ Barmar
指出问题在头上,但我想使用我喜欢用于PHP&amp ;;的格式化技术在遗漏空间问题上发布一个小变体。 MySQL的东西是这样的:
$ClassID = "1";
$sql = "SELECT subject.SubjectID, subject.Subject"
. " FROM subject"
. " LEFT JOIN class_subject ON subject.SubjectID = class_subject.SubjectID"
. " WHERE class_subject.ClassID = $ClassID"
. " ORDER BY SubjectID ASC"
;
此格式的基本概念可以压缩为三个项目:
SELECT
,FROM
,LEFT JOIN
,WHERE
& ORDER BY
分别在一行上。好处是可读性。但你也可以迅速和轻松注释掉一行或多行,而不必在开发时彻底重写您的查询。.
放在该行的左侧。如果您通常从左到右阅读,那么右侧确实可能被遗忘或遗漏。遵循这样的格式化结构&您将使您的调试生活更轻松。当他人帮助你时,它会让其他人更容易阅读。