具有不同字段的两个选择查询的并集

时间:2012-12-12 12:27:24

标签: mysql sql select sum

我有两张表empmasterallocation。我使用union来执行sql操作,以便从两个表中获取结果。 empmasterempid和其他empdetails。表格allocation包含来自empid的{​​{1}}作为foriegn密钥,另一个字段名为empmaster。我需要检索满足以下内容的per_alloc

  1. empdetails不在empmaster.empid

  2. allocation.empid
  3. empmaster.empid

  4. 我使用的MySQL查询是:

    allocation.empid and allocation.per_alloc < 100

    这只检索 select distinct(tbl_empmaster.emp_fname) from tbl_empmaster where tbl_empmaster.emp_id not in(select tbl_allocation.emp_id from tbl_allocation) union select distinct(tbl_empmaster.emp_fname) from tbl_empmaster where tbl_empmaster.emp_id in(select tbl_allocation.emp_id from tbl_allocation group by emp_id having sum(per_alloc) < 100) ,比如empdetails,我需要检索tbl_empmaster.emp_fname!当我尝试它时会出现很多错误,请问有没有人告诉我正确的方法呢?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT DISTINCT em.emp_fname, 0 alloc 
FROM tbl_empmaster em
WHERE em.emp_id NOT IN(SELECT emp_id FROM tbl_allocation)
UNION
SELECT DISTINCT em.emp_fname, SUM(a.per_alloc) alloc
FROM tbl_empmaster em 
INNER JOIN tbl_allocation a ON em.emp_id = a.emp_id 
GROUP BY a.emp_id 
HAVING SUM(a.per_alloc)<100

答案 1 :(得分:1)

好的,根据我对你的问题的理解,我发现了两个问题。

  1. 第二个select语句的子查询中有不必要的分组。只需写下select tbl_allocation.emp_id from tbl_allocation where tbl_allocation.per_alloc<100) *
  2. 就可以了
  3. 您问题的答案。将第二个选择语句更改为以下内容,它应该有效:
    select A.emp_fname, B.per_alloc from tbl_empmaster A join tbl_allocation B using(emp_id) where A.emp_id in(select C.emp_id from tbl_allocation C where C.per_alloc<100))
  4. **假设emp_id是主键*

相关问题