这个查询给了我空白的结果! Mysqli连接表

时间:2017-07-10 09:30:35

标签: php mysql mysqli

enter image description here 此图像显示有些行具有NULL值,我不需要它们。

此查询也需要很长时间才能加载..

基本上我想要的是

从我的数据库的两个表中获取值时出现问题。我在我的数据库中有两个表1是mem,第二个是付款mem存储名称和drawid用户付款表存储用户的抽奖和分期付款

用户每月向我们付款。因此,如果绘图ID为1的用户付费给我们,则两个表中的值为mem drawid = 1和name = something payment draw = 1 and installment = 2

mem中的drawid与付款中的draw相同

所以这些表有很多关系。现在我需要找到所有在4个月之前没有支付1个分期付款的会员名单。

 SELECT drawid,contact,dnd,mem.name,link,address, count(*) as numPayments,NULL numPaidPayments ,NULL PAID_CONTACT,NULL NAME_PAID FROM mem 
LEFT JOIN payment ON (mem.drawid = payment.draw) GROUP BY 
drawid HAVING numPayments < '4'
UNION
SELECT NULL drawid,NULL contact, NULL dnd, NULL name,NULL link, NULL address,NULL numPayments,COUNT(*) as numPaidPayments ,contact PAID_CONTACT,mem.name NAME_PAID  FROM mem 
INNER JOIN payment ON (mem.drawid = payment.draw) GROUP BY 
drawid HAVING numPaidPayments < '4' order by link desc 

我厌倦了解决这个问题,请给我一些建议,我一直试图解决这个问题......

我正在为表格结构添加图片。

在此输入图片说明 enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

似乎你想要的只是计算每个记忆的付款:

select 
  m.*,
  (select count(*) from payment p where p.draw = m.drawid) as num_paid_payments
from mem m;

仅限少于四次付款的人:

select *
from
(
  select 
    m.*,
    (select count(*) from payment p where p.draw = m.drawid) as num_paid_payments
  from mem m
) paid
where num_paid_payments < 4;

或者写得不同:

select 
  m.*,
  coalesce(cnt, 0) as num_paid_payments
from mem m
left join
(
  select draw, count(*) as cnt
  from payment
  group by draw
) p on p.draw = m.drawid
where coalesce(cnt, 0) < 4;

或者写得不同:

select 
  m.*, 
  count(p.draw) as num_paid_payments
from mem m
left join payment p on p.draw = m.drawid
group by m.drawid
having count(p.draw) < 4;