显示来自多个不同表的多个数据

时间:2013-08-27 05:40:10

标签: php mysql

我的数据库中有3个不同的表:

Leave {leave_id, leave_type, emp_id}
Employee {emp_id. emp_name, dept_id}
Department {dept_id, dept_name}

我希望根据leave_id选择leave_type,emp_name和dept_name。

我该如何撰写此查询?

由于

5 个答案:

答案 0 :(得分:1)

Select l.leave_type, e.emp_name, d.dept_name 
    FROM Leave l 
        JOIN Employee e ON l.emp_id = e.emp_id 
        JOIN Department d ON e.dept_id = l.dept_id 
    WHERE l.leave_id = '1'; //give leave_id which you want

使用上述查询。

答案 1 :(得分:0)

试试这个

select leave_type, emp_name ,dept_name from Leave, Employee, Department where Leave.emp_id = Employee.emp_id AND Employee.dept_id = Department.dept_id ;

答案 2 :(得分:0)

试试这个

SELECT leave_type, emp_name, dept_name 
FROM   Leave as l
JOIN   Employee as e ON e.emp_id = l.leave_id
JOIN   Department as d ON d.dept_id= l.leave_id
WHERE  leave_id = $id

答案 3 :(得分:0)

此选项将返回满足连接条件的所有行。

SELECT leave_type, emp_name, dept_name
FROM Leave
INNER JOIN Employee ON Leave.emp_id = Employee.emp_id
INNER JOIN Department ON Employee.dept_id = Department.dept_id
WHERE Leave.leave_id = ?

答案 4 :(得分:0)

使用 LEFT JOIN 强制加入,即使其中一个没有价值也是如此。

SELECT leave.leave_type, emp.emp_name, dept.dept_name
    FROM Employee emp
     LEFT JOIN Leave leave on emp.emp_id = leave.emp_id
     LEFT JOIN Department dept on dept.dept_id = emp.dept_id
 WHERE
 leave.leave_id='{$YOUR_VALUE}'