试图显示来自两个表的数据,而不是EXESTS

时间:2015-05-23 15:19:40

标签: php mysql

我有这个查询,它有效:

SELECT DISTINCT sid, name, last_name, tuition
FROM students 
WHERE EXISTS (SELECT * FROM payments 
WHERE payments.forMonth = 'May'
AND students.sid = payments.sid)

但是,当我尝试从付款表中添加几个列时,查询失败:

SELECT DISTINCT students.sid, students.name, students.last_name,
students.tuition, payments.amount, payments.forMonth
FROM students payments
WHERE EXISTS (
SELECT * 
FROM payments
WHERE payments.forMonth =  'Apr'
AND students.sid = payments.sid)

我在查询的上半部分尝试使用内部联接,但这会产生错误的结果。 有没有办法做到这一点?

(EXISTS条件的原因是我会在过滤器表单上进行切换,以显示已付款或未付款。)

1 个答案:

答案 0 :(得分:0)

外部查询使用内部联接并将其forMonth信息传递给子查询。可以这样想一想,如果不知道外部查询在哪个月看,那么现有语句怎么可能有用呢。

SELECT DISTINCT students.sid, students.name, students.last_name,
students.tuition, payments.amount, payments.forMonth
FROM students
 INNER JOIN payments ON students.sid = payments.sid
WHERE EXISTS (
SELECT * 
FROM payments p2 
WHERE p2.forMonth =  payments.forMonth )
And payments.forMonth = 'Apr'