查询使用空值或不等于提取结果

时间:2013-02-26 18:43:50

标签: mysql

我有像这样的mysql查询

SELECT s.admission_number, s.student_name, c.class, m.month, 
       f.fee, fr23.amount_received
FROM students s
LEFT JOIN fee_receipts fr ON s.id = fr.admission_number
LEFT JOIN fee_receipts_23_repeat fr23 ON fr.id = fr23.parent_id
JOIN class c ON s.class = c.id
LEFT JOIN fee f ON f.id = fr23.fee
LEFT JOIN months m ON m.id = fr23.month

显示这样的结果?

ad_num  student_name class   month    fee   amount_received 
779     A Jain      Nur     January Tuition   Fee   575.00
808     A Gupta     Nur     January Tuition   Fee   0.00
821     A Mohanty   Nur     NULL    NULL            NULL
818     ATiwari     Nur     FebruaryTuition   Fee   575.00
826     D Mishra    Nur     NULL    NULL      NULL
813     G Kaur      Nur     NULL    NULL      NULL  NULL
809     P Palai     Nur     NULL    NULL      NULL
822     S Agrawal   KG1     December Tuition  Fee   575.00
773     S Garg      KG1     NULL    NULL            NULL

现在,我试图通过排除那些已经付款但没有得到正确结果的人,按类别获得未付费用的学生名单。我在上述查询中添加的条件就像这样

where fr23.amount_received is NULL and c.class = 'Nur' and m.month != 'January'

我希望结果是它会列出所有未支付1月份费用的学生,但它会给我一个空的结果集。

实际上我正在尝试找到没有付款条目的学生,这意味着列月份,费用和amount_received将具有空值。

我不确定我是否采取了正确的方法?

2 个答案:

答案 0 :(得分:1)

将您的条件移至JOIN ON条件:

SELECT s.admission_number, s.student_name, c.class, m.month, 
       f.fee, fr23.amount_received
FROM students s
LEFT JOIN fee_receipts fr ON s.id = fr.admission_number
LEFT JOIN fee_receipts_23_repeat fr23 ON fr.id = fr23.parent_id
    AND fr23.amount_received is NULL   -- Moved to here
JOIN class c ON s.class = c.id
LEFT JOIN fee f ON f.id = fr23.fee
LEFT JOIN months m ON m.id = fr23.month
    AND (m.month != 'January' OR m.month IS NULL) -- Added IS NULL check

答案 1 :(得分:0)

经典的空陷阱!

null比较不像你想象的那样......

change m.month != 'January'

to

coalesce(m.month,'') != 'January'