MySQL查询 - 显示不在另一个表中的结果

时间:2009-07-25 17:13:31

标签: sql mysql

我有这样的查询:

SELECT lesson.id, p1.first_name, p1.surname, start_time, instrument.name 
FROM  lesson, person AS p1, person AS p2, instrument, invoice_lesson
WHERE lesson.student = p1.id
AND   lesson.teacher = p2.id
AND   instrument.id  = lesson.instrument_id
ORDER BY surname

但是,我想修改它,以便它只显示lesson.id不在表invoice_lesson.lesson_id中的结果。这是一个相关的查询吗?我该怎么做?

3 个答案:

答案 0 :(得分:4)

您可以使用外部联接执行此操作:

SELECT lesson.id, p1.first_name, p1.surname, start_time, instrument.name 
FROM  lesson l JOIN person p1 ON l.student = p1.id
JOIN person p2 ON l.teacher = p2.id
JOIN instrument i ON i.id = l.instrument_id
LEFT JOIN invoice_lesson il ON l.id = il.lesson_id
WHERE il.lesson_id IS NULL
ORDER BY surname

这种方法比相关子查询方法快得多。

答案 1 :(得分:0)

最简单的方法:

SELECT lesson.id, p1.first_name, p1.surname, start_time, instrument.name 
FROM  lesson, person AS p1, person AS p2, instrument, invoice_lesson
WHERE lesson.student = p1.id
AND   lesson.teacher = p2.id
AND   instrument.id  = lesson.instrument_id
AND   lesson.id NOT IN (SELECT lesson_id FROM invoice_lesson)
ORDER BY surname

可能不是最快的一个:)

Tomasz Kopczuk

答案 2 :(得分:0)

尝试使用JOIN

 SELECT lesson.id, p1.first_name, p1.surname, start_time, instrument.name 
 FROM  lesson, person AS p1, person AS p2, instrument, invoice_lesson
 JOIN  invoice_lesson
 ON    lession.id = invoice_lession.lesson_id
 WHERE lesson.student = p1.id
 AND   lesson.teacher = p2.id
 AND   instrument.id  = lesson.instrument_id
 ORDER BY surname