mysql查询以计数联接三个表中的行数并计算一个表的行数

时间:2018-07-17 10:38:01

标签: mysql sql mysqli

我在 MYSQL 查询中遇到问题。 我有三个表,一个是voucher表,其他是客户端,第三个是voucher_client。 在voucher_client表中,我具有与凭证表相关的凭证id列,并且我想对来自客户机表的相关行进行计数。 就像如果优惠券表的id为2,而优惠券的客户为2,则查询将从客户表age_group的列中进行检查,其中age_group是成人,儿童或婴儿 这里有一些表格的图片以获取更多细节。 请帮帮我

优惠券表

enter image description here

客户表

enter image description here

优惠券客户表

enter image description here

我正试图这样做

  SELECT `v`.*, `a`.`name` as `agent_name`, COUNT(CASE WHEN c.age_group = 'Adult' THEN c.id END) AS t_adult, COUNT(CASE WHEN c.age_group = 'Child' THEN c.id END) AS t_child, COUNT(CASE WHEN c.age_group = 'Infant' THEN c.id END) AS t_infant, COUNT(c.id) as total FROM `voucher` `v` JOIN `voucher_client` `vc` ON `vc`.`voucher_id`=`v`.`id` JOIN `client` `c` ON `vc`.`client_id`=`c`.`id` JOIN `tbl_users` `a` ON `a`.`userId`=`v`.`agent_id` LEFT JOIN `voucher_hotel` `vh` ON `vh`.`voucher_id`=`v`.`id` WHERE `v`.`isDeleted` =0 GROUP BY `v`.`id` ORDER BY `v`.`id` DESC 

预期的输出

voucher_id t_adult    t_child    t_infant
 1            2           0         0
 2            1           0         0

1 个答案:

答案 0 :(得分:1)

如果仅想在结果中显示v.id,则在查询中将v.*替换为v.id

(顺便说一句,大多数数据库在进行分组依据时甚至都不允许*。MySql在这方面偏离了ANSI SQL标准。)

如果需要以1-N关系连接到额外的表?然后,您可以计算不同的值。这样总数只能反映唯一的clientid。

SELECT
  v.id AS voucher_id,
  COUNT(DISTINCT CASE WHEN c.age_group = 'Adult'  THEN c.id END) AS t_adult,
  COUNT(DISTINCT CASE WHEN c.age_group = 'Child'  THEN c.id END) AS t_child,
  COUNT(DISTINCT CASE WHEN c.age_group = 'Infant' THEN c.id END) AS t_infant
  -- , COUNT(*) as total
  -- , COUNT(c.id) as total_clientid -- count on value doesn't count NULL's
  -- , COUNT(DISTINCT c.id) as total_unique_clientid
FROM voucher v
JOIN voucher_client vc ON vc.voucher_id = v.id
JOIN client c ON c.id = vc.client_id
-- LEFT JOIN voucher_hotel vh ON vh.voucher_id = v.id
WHERE v.isDeleted = 0
--  AND c.age_group = 'Adult' -- uncomment this to only count the adults
GROUP BY v.id 
ORDER BY v.id