MySQL查询以检查查询是否返回任何重复项

时间:2018-02-03 03:07:50

标签: mysql

我试图检查MySQL查询以确保它只为每个txn_feed.id返回一个结果。然而,下面的语句返回id = 1和txns = 36963的单个结果。我希望看到txns = 1的所有txn_id对于大多数/全部而不是txns> 1表示任何重复。我知道这将是一件简单的事情,但我是SQL的新手并且无法看到它。

select tf.id, count(*) as txns
from txn_feed as tf left join 
     kiosk as k
     on tf.kiosk_number = k.number left join
     kiosk_deployment as kd on k.id = kd.machine_id
where tf.date_authorised > kd.installed_date and
      ((kd.status = 'Installed') or (kd.status = 'Removed' and tf.date_authorised < kd.uninstalled_date))
order by txns desc;

提前谢谢。

2 个答案:

答案 0 :(得分:1)

您使用了汇总功能count(),但错过了group by。通过应用group by,它将首先使该组具有不同的ID并返回计数。

select tf.id, count(*) as txns
from txn_feed as tf left join 
     kiosk as k
     on tf.kiosk_number = k.number left join
     kiosk_deployment as kd on k.id = kd.machine_id
where tf.date_authorised > kd.installed_date and
      ((kd.status = 'Installed') or (kd.status = 'Removed' and tf.date_authorised < kd.uninstalled_date))
      group by tf.id
order by txns desc;

答案 1 :(得分:0)

您错过了group by

select tf.id, count(*) as txns
from txn_feed tf left join 
     kiosk as k
     on tf.kiosk_number = k.number left join
     kiosk_deployment kd
     on k.id = kd.machine_id
where tf.date_authorised > kd.installed_date and
      ((kd.status = 'Installed') or
       (kd.status = 'Removed' and tf.date_authorised < kd.uninstalled_date)
      )
group by tf.id
order by txns desc;