我有两个案例表。 tbl_emp是主表,说: -
----------------------------------------------------------
tbl_emp
----------------------------------------------------------
emp_id emp_name
1 Peter
2 Matt
3 Jacob
----------------------------------------------------------
并且详细信息表中包含员工的家庭详细信息.......
-----------------------------------------------------------------
tbl_family
----------------------------------------------------------------
family_id emp_id relation name age
-----------------------------------------------------------------
1 1 WIFE Susan 32
2 1 SON Jack 3
3 2 DAUGHTER Hannah 4
4 2 WIFE Leah 29
5 1 WIFE Anna 38
6 3 MOTHER Loran 73
7 2 MOTHER Sofia 81
------------------------------------------------------------------
我想要一个查询来了解所有员工在tbl_family中有一个特定的“关系”条目以及谁不具备。例如,我管理了对具有WIFE条目的雇员的以下查询
select * from tbl_emp, tbl_family where
tbl_emp.emp_id = tbl_family.emp_id and
tbl_family.relation = 'WIFE'
此查询正确返回Peter和Matt。但我需要查询三个问题。首先。给我在tbl_family没有WIFE条目的员工。即输出应该是
---------------------------------------
emp_id emp_name
---------------------------------------
3 Jacob
---------------------------------------
seconldy,为其提供的数据集记录两个WIFE条目(或任何其他关系)
-----------------------------------------
emp_id emp_name
-----------------------------------------
1 Peter
-----------------------------------------
最后,所有拥有WIFE和MOTHER条目的员工。这个查询将返回
-----------------------------------------
emp_id emp_name
-----------------------------------------
2 Matt
-----------------------------------------
我已编辑了所有结果输出的问题。感谢。
答案 0 :(得分:1)
第一点:
--wihout wife
select tbl_emp.*
from tbl_emp
left join tbl_family
on
tbl_emp.emp_id = tbl_family.emp_id and tbl_family.relation = 'WIFE'
where tbl_family.emp_id IS NULL;
第二点:
--having any relation at least twice
select tbl_emp.id, tbl_emp.name, tbl_family.relation
from tbl_emp
left join tbl_family
on
tbl_emp.emp_id = tbl_family.emp_id
group by tbl_emp.id, tbl_emp.name, tbl_family.relation
having count(tbl_family.emp_id) > 1;
第三点:
--having WIFE, SON AND DAUGHTER.
select tbl_emp.id, tbl_emp.name
from tbl_emp
left join tbl_family
on
tbl_emp.emp_id = tbl_family.emp_id and (
tbl_family.relation = 'WIFE' or
tbl_family.relation = 'SON' or
tbl_family.relation = 'DAUGHTER'
)
group by tbl_emp.id, tbl_emp.name
having count(distinct tbl_family.relation) >= 3;
答案 1 :(得分:1)
第三点:
SELECT tbl_emp.*
FROM tbl_emp
INNER JOIN tbl_family tf1
ON tbl_emp.emp_id = tf1.emp_id AND tf1.relation = 'WIFE'
INNER JOIN tbl_family tf2
ON tbl_emp.emp_id = tf2.emp_id AND tf2.relation = 'MOTHER';
答案 2 :(得分:0)
你应该玩tbl_family.relation = 'WIFE'
您可以使用例如(tbl_family.relation = 'WIFE' OR tbl_family.relation = 'MOTHER' OR tbl_family.relation = 'DAUGHTER'
)
此外,您可以使用OUTER JOIN
查找没有家人的人