我有以下表格:
表名::学生
studentid studentname
1001 Charlie Sheen
1002 John Cryer
表名:: studentpayment1
paymentid studentid fee_month fee_year totalamount
1234 1001 February 2012 $500
4321 1002 January 2012 $1500
表名:: studentpayment2
id pid fee_type fee_amount
1 1234 Monthly Fee $500
2 4321 Exam Fee $1500
现在,我正在试图找出未支付2012年2月份“月费”的学生的姓名。
我尝试了以下代码,但它没有生成正确的信息。
$year="2012"; $month="February"; $fee_type="Monthly Fee";
SELECT DISTINCT studentid,
studentname
FROM student
WHERE NOT EXISTS (SELECT *
FROM studentpayment1
JOIN studentpayment2
ON studentpayment1.paymentid = studentpayment2.pid
WHERE fee_month = '$month'
AND fee_type = '$fee_type'
AND fee_year = '$year'
AND student.studentid = studentpayment1.studentid)
LIMIT $perPage
如何修复此查询?
答案 0 :(得分:1)
这将为您提供所有在2012年2月没有支付任何费用,2012年2月没有任何费用或2012年2月没有月费的学生
SELECT * FROM student s
LEFT JOIN studentpayment1 sp1
ON s.studentid = sp1.studentid
AND ((sp1.fee_month = 'February' AND sp1.fee_year = '2012') OR sp1.fee_month is null)
LEFT JOIN studentpayment2 sp2
ON sp1.paymentid = sp2.pid AND ( sp2.fee_type = 'Monthly Fee' OR sp2.fee_type is null)
WHERE sp1.fee_month is null or sp2.fee_type is null
祝你好运
BTW这里有一些很好的架构建议:将选项卡上的所有主键更改为'id'并与你命名foriegn键一致:学生表的primay键应该只是studentpayment1中的'id'表应该有一个名为student_id的列。 studentpayment2表应该有一个指向studentpayment1的列,名为studentpayment1_id而不是'pid'。
答案 1 :(得分:0)
您的变量不应该在单引号内:
"WHERE fee_month = '".$month."' "
更好的方法是绑定变量。
答案 2 :(得分:0)
我没有尝试过实时运行此查询,但这应该会帮助你。
select distinct studentid from student where studentid NOT EXISTS (select studentid from studentpayment1 where fee_month = '$month'
AND fee_type = '$fee_type'
AND fee_year = '$year')
或
select distinct studentid from student where NOT EXISTS (select studentid from studentpayment1 where fee_month = '$month'
AND fee_type = '$fee_type'
AND fee_year = '$year')
答案 3 :(得分:0)
如果你的子查询是正确的(我没看过它),下面的查询应该可以正常工作
SELECT DISTINCT studentid,studentname FROM student WHERE
studentid NOT IN (SELECT studentid FROM studentpayment1 JOIN studentpayment2 ON studentpayment1.paymentid=studentpayment2.pid WHERE
fee_month='$month' AND fee_type='$fee_type' AND fee_year='$year' AND student.studentid=studentpayment1.studentid ) LIMIT $perPage
答案 4 :(得分:0)
看起来这会做的事情:
$year="2012"; $month="February"; $fee_type="Monthly Fee";
$students_with_debt = "SELECT name FROM student WHERE studentid NOT IN (SELECT studentid FROM studentpayment1 p1 INNER JOIN studentpayment2 p2 ON p1.paymentid = p2.pid WHERE fee_month = '$month' AND p1.fee_year = '$year' AND p2.fee_type = '$fee_type');"
答案 5 :(得分:-1)
请尝试使用LEFT JOIN:
SELECT student.studentid, student.studentname FROM student
LEFT JOIN studentpayment1 ON studentpayment1.studentid = student.studentid
AND studentpayment1.fee_month = ?
AND studentpayment1.fee_year = ?
LEFT JOIN studentpayment2 ON studentpayment2.pid = studentpayment1.paymentid
AND studentpayment2.fee_type = ?
WHERE studentpayment2.id IS NULL
确保将索引放在fee_month,fee_year和fee_type上,并替换所有?用你的变量。