mysql查询通过检查另一个表

时间:2016-06-14 23:42:55

标签: php mysql

我在一个数据库中有两(2)个表,我想显示所有未付款的成员:

我试过这个但没有工作:

SELECT members.*, payments.amount='', paid_for='fee';

表1“成员”,ID,ROLL NO和NAMES

表2“付款”,ID为ROLL NO,AMOUNT,PAID_FOR,DATE,STATUS,RECEIPT NO

我想选择AMOUNT为空的所有地方,付费付费

这意味着如果没有付款,它会将数据库中的所有成员显示为未付款。

2 个答案:

答案 0 :(得分:0)

这样的事情:

SELECT m.ID,m.ROLL_NO,m.NAMES,p.AMOUNT,p.PAID_FOR,p.DATE,p.STATUS,p.RECEIPT_NO

       FROM MEMBERS m  INNER JOIN PAYMENTS p

                 ON m.ROLL_NO = p.ROLL_NO

       WHERE (m.AMOUNT IS NULL OR m.AMOUNT='') AND p.PAID_FOR='fee'

       GROUP BY m.NAMES;

答案 1 :(得分:0)

如果您希望没有付款的所有成员,您可能需要使用inner join,并根据您的要求,您的条件应为and,请尝试关注;)< / p>

select distinct t1.*
from members t1
inner join payments t2
on t1.roll_no = t1.roll_no
and t2.paid_for = 'fee' and (t2.amount is null or t2.amount = '')

或者可以使用exists之类的:

select t1.*
from members t1
where exists (
    select 1 
    from payments t2 
    where t1.roll_no = t2.roll_no
    and t2.paid_for = 'fee'
    and (t2.amount is null or t2.amount = '')
)