我有两张 table empmaster
和allocation
。我用过union
进行sql操作以获取两个表的结果。 empmaster
有empid
及其他empdetails
。表allocation
包含empid
来自empmaster
作为外键,另一个名为 per_alloc
的字段。我需要检索empdetails
满足:
empmaster.empid
不在allocation.empid
中.empmaster.empid
在allocation.empid and allocation.per_alloc < 100
.
我使用的MySQL查询是:
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
,我需要检索sum(per_alloc) from select tbl_allocation
!!!当我尝试时,它给出了很多错误,有人可以告诉我正确的方法吗?
最佳答案
试试这个:
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
关于mysql - 具有不同字段的两个选择查询的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13839771/