帮助MySQL连接3个表

时间:2011-06-08 21:52:50

标签: mysql

我正在使用以下表格的注册系统: 人(姓名等),课程(课程日期),注册(关联表pid,cid)

Person
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
| name  | text    | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+

Example Data:
select * from person;
+-----+--------+
| id  | name   |
+-----+--------+
| 101 | Graham |
| 102 | Lisa   |
| 103 | John   |
+-----+--------+

Course
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
| name  | text    | YES  |     | NULL    |       |
| date  | date    | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+

select * from course;
+----+---------+------------+
| id | name    | date       |
+----+---------+------------+
|  1 | Hip Hop | 2011-06-08 |
|  2 | Dancing | 2006-06-23 |
|  3 | Running | 2007-07-08 |
+----+---------+------------+

Registration
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
| pid   | int(11) | YES  |     | NULL    |       |
| cid   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+

select * from registration;
+----+------+------+
| id | pid  | cid  |
+----+------+------+
|  1 |  101 |    1 |
|  2 |  101 |    2 |
|  3 |  103 |    2 |

+----+------+------+

我想找到过去两年内没有注册记录的人。我试图根据日期计算加入表格,但似乎没有这种方式。这可能是使用mysql还是我尝试使用一个查询错误的方法?

查询我想出了:

select * from
(person left join registration on person.id = registration.pid)
left join course on course.id = registration.cid
AND DATE_FORMAT(`course`.`date`, "%m.%Y") > DATE_FORMAT( DATE_SUB(NOW(), INTERVAL 2 YEAR),"%m.%Y")
WHERE
registration.id IS NULL;
+-----+------+------+------+------+------+------+------+
| id  | name | id   | pid  | cid  | id   | name | date |
+-----+------+------+------+------+------+------+------+
| 102 | Lisa | NULL | NULL | NULL | NULL | NULL | NULL |
+-----+------+------+------+------+------+------+------+

它应该列出人102和103,因为两个注册都超过2年,并且没有其他新课程日期的记录可以找到...

1 个答案:

答案 0 :(得分:1)

使用NOT EXISTS子句给这一点:

select p.* from person p
where not exists (select 1 from person px
                  join registration rx on px.id = rx.pid
                  join course cx on rx.cid = cx.id
                  where px.id = p.id
                  and cx.date > DATE_SUB(NOW(), INTERVAL 2 YEAR))