Mysql自联接不提供准确的数据

时间:2016-06-22 12:41:17

标签: mysql sql database self-join

我有如下的员工表。

emp_id      emp_name            emp_supv
4081        Nancy Brown         0
4083        Peter Parker        4081
4055        Jacob Miller        4083
4058        Mary Ray            4083
4060        Jane Smith          4081
4061        Bob Hunter          4081
4066        Nancy Smith         0
4061        Bob Smith           4066

我希望LIKE查询关键字Nancy,它应该返回如下的结果(父记录的名称像Nancy及其子记录。)。

4081        Nancy Brown       0
4083        Peter Parker      4081
4060        Jane Smith        4081
4061        Bob Hunter        4081
4066        Nancy Smith       0
4061        Bob Smith         4066

尝试使用以下查询,但它只返回子记录而不是父记录emp_supv 0

SELECT sa.id AS id,sa.name AS Name,
sa2.id AS child_id, sa2.name AS child_name
FROM employees AS sa LEFT OUTER JOIN employees AS sa2
ON sa.emp_supv = sa2.emp_id where sa2.emp_name LIKE '%Nancy%';

2 个答案:

答案 0 :(得分:1)

尝试使用if on null作为

    SELECT sa.emp_id AS id,sa.emp_name AS Name, 
    sa.emp_supv AS child_id, sa2.emp_name AS child_name
    FROM Employees  AS sa 
    LEFT OUTER JOIN employees AS sa2
    ON case when ifnull(sa.emp_supv,0)=0 then sa.emp_id else sa.emp_supv end= sa2.emp_id 
where sa2.emp_name LIKE '%Nancy%'

答案 1 :(得分:1)

我跳这会帮助你:

SELECT DISTINCT a.* FROM employee AS a
JOIN employee AS b
ON a.emp_id=b.emp_id
WHERE a.emp_name LIKE '%nancy%' OR a.emp_supv IN (SELECT emp_id FROM employee WHERE emp_name LIKE '%nancy%')