第一个选择和第二个选择的不同值(UNION WITH GROUP BY)

时间:2016-01-06 02:58:43

标签: mysql join group-by union

我有一个表用户

user_id | ui_id
--------+-------
   4    |   16
--------+-------
   5    |   17
--------+-------
   9    |   21

USER_INFO

ui_id |      fname      |     lname
------+-----------------+--------------
  16  |     Joanalyn    |    Lalicon
------+-----------------+--------------
  17  |   Jose Allan    |   Dela Cruz
------+-----------------+--------------
  21  |       Steve     |   Dela Cruz

加时

ot_id | approve_by
------+------------
  3   |     4
------+------------
  6   |     9
------+------------
  8   |     5
------+------------
  9   |     9
------+------------
  16  |     4

最后 loa

loa_id| approve_by
------+------------
  4   |     9
------+------------
  6   |     4

我想在一个查询中将Full Nameqtyqty2作为字段。但是不能让它发挥作用。我可以得到ot_id count和loa_id count的总和,但不能将值分开。

我的疑问:

SELECT name,qty2 <---- value from second select
FROM
(SELECT CONCAT(ui.fname,' ',ui.lname) AS name,
        COUNT(o.ot_id) AS qty
FROM overtime o
INNER JOIN users u ON o.approve_by=u.user_id
INNER JOIN user_info ui ON u.ui_id=ui.ui_id
GROUP BY ui.ui_id

UNION ALL

SELECT CONCAT(ui.fname,' ',ui.lname) AS name,
        COUNT(l.loa_id) AS qty2 <----- can't get this value
FROM loa l
INNER JOIN users u ON l.approve_by=u.user_id
INNER JOIN user_info ui ON u.ui_id=ui.ui_id
GROUP BY ui.ui_id) ui

GROUP BY name

我无法获得qty2,但qty正在运作。如果我选择SUM(qty),则会将ot_idloa_id

相加

我想要这样的事情:

       Name          |        qty       |       qty2    
---------------------+------------------+-------------------
  Joanalyn Lalicon   |        2         |         1
---------------------+------------------+-------------------
 Jose Allan Dela Cruz|        1         |         0
---------------------+------------------+-------------------
   Steve Dela Cruz   |        2         |         1

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT CONCAT(ui.fname, ' ', ui.lname) AS name
     , COUNT(o.ot_id) AS qty
     , (SELECT COUNT(*) FROM loa WHERE approve_by = u.user_id) AS qty2
  FROM users u
  JOIN user_info ui ON ui.ui_id = u.ui_id
  LEFT JOIN overtime o ON o.approve_by = u.user_id
 GROUP BY u.user_id;

<强> SQL Fiddle