如何在join query中使用count()获取数据行

von4xj4u  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(350)

我有两张table inventory 以及 tickets ,我想获取存储在库存中的机器详细信息,并报告3张以上的票据。这两个表之间的公共行是 machine_name .

inventory                                 tickets

machine_name|location|macaddress          tkt_no|machine_name|problem
---------------------------------------   ----------------------------
fad.dfsd.dg|lab1     |aa:bb:cc:dd:ee:ff   01    |fgr.sds.ss  |Network
fgr.sds.ss |lab3     |bb:cc:dd:ee:ff:aa   02    |fgr.sds.ss  |HDD  
ggr.sds.se |lab1     |11:cc:dd:ee:ff:aa   03    |fad.dfsd.dg |HDD 
                                          04    |fad.dfsd.dg |Monitor
                                          05    |fad.dfsd.dg |Other
                                          06    |fad.dfsd.dg |Power
                                          07    |ggr.sds.se  |Monitor
                                          08    |fgr.sds.ss  |Power
                                          09    |fgr.sds.ss  |Other
                                          10    |fgr.sds.ss  |Monitor
                                          11    |fgr.sds.ss  |Mouse
                                          12    |ggr.sds.se  |Power

这就是我尝试过的:

SELECT i.machine_name, i.location, i.macaddress, COUNT(t.machine_name) AS cnt
FROM inventory AS i
RIGHT JOIN tickets AS t USING(machine_name)
GROUP BY t.machine_name
HAVING cnt > 3

我希望这个查询返回

machine_name | location |macaddress        | cnt
------------------------------------------------
fad.dfsd.dg  | lab1     |aa:bb:cc:dd:ee:ff | 4
fgr.sds.ss   | lab3     |bb:cc:dd:ee:ff:aa | 6

但是除了count之外,我得到了所有的空值

machine_name | location |macaddress  | cnt
------------------------------------------
null         | null     |null        | 4
null         | null     |null        | 6

有人能帮助我如何获得我想要的结果吗?

js4nwp54

js4nwp541#

SELECT i.machine_name, i.location, i.macaddress, COUNT(t.machine_name) AS cnt
FROM inventory AS i
JOIN tickets AS t USING(machine_name)
GROUP BY i.machine_name, i.location, i.macaddress
HAVING cnt > 3

相关问题