mysql查询,计算连接三个表的行数,并计算一个表的行数

h7wcgrx3  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(412)

我在mysql查询中遇到问题。我有三个表一个是凭单表其他客户和第三个是凭单客户。在凭证\客户表中,我有凭证 id 列,我想从客户机表中计算相关行。就像凭证表 id 2和凭证客户机为2,则查询将从客户机表中进行检查 age_group 列,其中 age_group 这里有成人、儿童或婴儿的一些table图片,以了解更多细节。请帮帮我
凭证表

客户端表

凭证客户端表

我正试着这样做

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
nbnkbykc

nbnkbykc1#

如果你只想展示 v.id 在结果中,然后替换 v.*v.id 在查询中。
(顺便说一句,大多数数据库甚至不允许 * 当有分组的时候。mysql在这方面偏离了ansi sql标准。)
如果你需要加入一个1-n关系的额外表?然后可以计算不同的值。所以总数只能反映唯一的客户ID。

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

相关问题