我有一个MySQL Left Join问题.
我有三张桌子,我正在尝试加入.
人员表:
CREATE TABLE person ( id INT NOT NULL AUTO_INCREMENT, type ENUM('student', 'staff', 'guardian') NOT NULL, first_name CHAR(30) NOT NULL, last_name CHAR(30) NOT NULL, gender ENUM('m', 'f') NOT NULL, dob VARCHAR(30) NOT NULL, PRIMARY KEY (id) );
学生表:
CREATE TABLE student ( id INT NOT NULL AUTO_INCREMENT, person_id INT NOT NULL, primary_guardian INT NOT NULL, secondary_guardian INT, join_date VARCHAR(30) NOT NULL, status ENUM('current', 'graduated', 'expelled', 'other') NOT NULL, tutor_group VARCHAR(30) NOT NULL, year_group VARCHAR(30) NOT NULL, PRIMARY KEY (id), FOREIGN KEY (person_id) REFERENCES person(id) ON DELETE CASCADE, FOREIGN KEY (primary_guardian) REFERENCES guardian(id), FOREIGN KEY (secondary_guardian) REFERENCES guardian(id), FOREIGN KEY (tutor_group) REFERENCES tutor_group(name), FOREIGN KEY (year_group) REFERENCES year_group(name) );
事件表:
CREATE TABLE incident ( id INT NOT NULL AUTO_INCREMENT, student INT NOT NULL, staff INT NOT NULL, guardian INT NOT NULL, sent_home BOOLEAN NOT NULL, illness_type VARCHAR(255) NOT NULL, action_taken VARCHAR(255) NOT NULL, incident_date DATETIME NOT NULL, PRIMARY KEY (id), FOREIGN KEY (student) REFERENCES student(id), FOREIGN KEY (staff) REFERENCES staff(id), FOREIGN KEY (guardian) REFERENCES guardian(id) );
我想要选择的是第9年每个学生的名字,姓氏和事件数量.
这是我对查询的最佳尝试:
SELECT p.first_name, p.last_name, COUNT(i.student) FROM person p, student s LEFT JOIN incident i ON s.id = i.student WHERE p.id = s.person_id AND s.year_group LIKE "%Year 9%";
然而,它忽略了没有事故的学生,这不是我想要的 - 他们应该被显示但是数量为0.如果我删除了左连接和计数,那么我得到了所有学生,正如我所期望的那样.
我可能误解了左连接,但我认为应该这样做,基本上我正在尝试做什么?
谢谢你的帮助,
亚当
你做的很好,你只是错过了group by子句
SELECT p.first_name, p.last_name, COUNT(i.student) FROM person p, student s LEFT JOIN incident i ON s.id = i.student WHERE p.id = s.person_id AND s.year_group LIKE "%Year 9%" GROUP BY p.first_name, p.last_name;
这是一些测试数据
insert into person values(1, 'student', 'Alice', 'Foo', 'f','1970-01-01'); insert into person values(2, 'student', 'Bob', 'Bar', 'm','1970-01-01'); insert into student values(1,1,0,0,'', 'current','','Year 9'); insert into student values(2,2,0,0,'', 'current','','Year 9'); insert into incident values(1,1,0,0,0,'flu','chicken soup', '2008-01-08');
以下是添加到组中的查询输出:
+------------+-----------+------------------+ | first_name | last_name | COUNT(i.student) | +------------+-----------+------------------+ | Alice | Foo | 1 | | Bob | Bar | 0 | +------------+-----------+------------------+
您可以通过从where子句创建join子句并对person id进行分组来进一步清理查询:
SELECT p.first_name, p.last_name, COUNT(i.student) FROM person p INNER JOIN student s ON(p.id = s.person_id) LEFT JOIN incident i ON(s.id = i.student) WHERE s.year_group LIKE "%Year 9%" GROUP BY p.id;