加入两个有多个条件的表

时间:2015-11-18 08:00:31

标签: php mysql session

我有两张桌子并且选择了4月份,会话是1

studentprofile

sud_id   name        session_id

1         kp            1

2         kishan        1

3          raj          1
4          arti         1        not any fee submitted till now
5          kp           2        session is diffrent

fee_generate

fee_id    stud_id    fee_balance  delay    name     session_id   feemonth 

1            1         0            0       kp         1         april

2            2         10           10     kishan      1         april
3            2         0            0      kishan      1         april      he cleared his balance

4            3         0            0      raj        1          march      fee not submitted in this month

5            5         0            0      kp         1          april       here session is diffrent...  so nothing to do with this session

我想向那些未提交费用或有任何余额或任何延迟的学生展示,直到选定的月份(在这种情况下是4月),会话1表示我想要展示如下:

arti and raj

我当前的查询:

select s.* from studentprofile s 
            left join 
            fee_generate f 
            on 
            s.stud_id=f.stud_id 
            where  

            s.session_id='$session_id'  and s.stud_class='$class' 
            and 
            (  f.stud_id is null or  ( f.feemonth='$selected_fee_month1' and (f.delay>0.00 or f.fee_balance>0.00)))
                   order by s.name desc

我无法使用任何join编写查询。我的第二个问题是名称列在两个表中都很常见。因此,所选名称列应来自studentprofile表,并根据studentprofile表按名称排序。

1 个答案:

答案 0 :(得分:0)

尝试进行左外连接,在你可以检查fee_id是否为空(无记录)或延迟/ fee_balance是否大于0的位置。 像这样

SELECT
    s.*
FROM studentprofile s
LEFT OUTER JOIN fee_generate fg
    ON fg.stud_id = s.sud_id
    AND fg.feemonth='$selected_fee_month1'
WHERE 
    s.session_id='$session_id'
    AND s.stud_class='$class' 
    AND (fg.fee_id IS NULL
        OR fg.delay > 0
        OR fg.fee_balance > 0)

未经过测试的代码

提示:您的feemonth字段不包含年份信息,我认为创建一个费用字段也是个好主意。