简体   繁体   English

MySQL从两个表中选择联接

[英]Mysql select from two tables join

i have two tables "employees" and "dependents", 我有两个表“员工”和“家属”,

  Employees |employee_No| Employee_name | |1558 | Bean | |1557 | Juliet | |1556 | Zeke | Dependents |employee_No| dependent_name | relationship| |1558 | Kelvin | Son | |1558 | Mary | Daughter | |1556 | Janet | Spouse | 

is there a way i could get this data in one MySQL statement and display using php ie loop employees and dependent under that employee then move to the next employee. 有没有一种方法可以在一个MySQL语句中获取此数据并使用php显示,即循环雇员和该雇员下的从属,然后移至下一个雇员。

current php code is 当前的PHP代码是

$employees = select_all_employees()
foreach ($employees as $covered){
  echo $covered['Employee_name'].'<br/>';
$get_dependent = $select_dependent($covered["employee_No "]);
 if($get_dependent != 0){
     foreach($get_dependent as $details){
      echo $details['dependent_name '].' '.$details['relationship'].'<br/>';
     }
  }
}

this takes too much time to load when there are thousand employees and dependents 当有成千上万的员工和家属时,这会花费太多时间

expected outcome 预期结果

|employee_No| dependent_name | relationship|
--------------------------------------------
|1558       | Bean           | principal   |
|1558       | Kelvin         | Son         |
|1558       | Mary           | Daughter    |
|1557       | Juliet         | principal   |
|1556       | Zeke           | principal   |
|1556       | Janet          | Spouse      |

The easiest way to get the results you want is with a UNION of the rows of the Employees table with the JOIN of the Employees with their Dependents . 得到你想要的结果,最简单的方法是使用UNION中的行Employees表与JOIN的的Employees与他们的Dependents We do this UNION as a derived table so that we can then order the results by employee_No and also place the principal first for each employee_No . 我们将此UNION做为派生表,以便随后可以按employee_No排序结果,也可以将principal放在每个employee_No前面。 By doing it this way your PHP code becomes a simple loop over all the results. 通过这种方式,您的PHP代码将成为所有结果的简单循环。

SELECT employee_No, Employee_name AS dependent_name, 'principal' AS relationship
FROM Employees
UNION ALL
SELECT e.employee_No, d.dependent_name, d.relationship
FROM Employees e
JOIN Dependents d on d.employee_No = e.employee_No
ORDER BY employee_No DESC, relationship = 'principal' DESC

Output: 输出:

employee_No dependent_name  relationship
1558        Bean            principal
1558        Mary            Daughter
1558        Kelvin          Son
1557        Juliet          principal
1556        Zeke            principal
1556        Janet           Spouse

Demo on dbfiddle dbfiddle上的演示

How about this query: 该查询如何:

SELECT a.*, "principal" as 'relationship' FROM Employees a UNION SELECT b.* FROM Dependents b ORDER BY employee_no DESC

DBFIDDLE here DBFIDDLE在这里

You can use join or Map the columns. 您可以使用联接或映射列。 Check the index in both the tables for your slowness of query. 检查两个表中的索引以确保查询速度慢。 Index should be employee_No in both the tables. 两个表中的索引都应为employee_No And then loop your query output. 然后循环查询输出​​。

<?php
    $qryOutput = array();
    $query = "SELECT A.*, B.* FROM Employees A LEFT JOIN Dependents B ON   A.employee_No=B.employee_No" // query

    $qryOutput = execute_Query($query); // Check this syntax. For Execute query


    // Loop through your Query Output
    foreach ($qryOutput as $key => $value) 
    {   echo $value["employee_No"]." ".$value["dependent_name"]." ".$value["relationship"]; }

 ?>

You can use either INNER JOIN or LEFT JOIN to actualize it. 您可以使用INNER JOINLEFT JOIN来实现它。

Try something like this. 尝试这样的事情。 Though I have not tested the code. 虽然我没有测试代码。

Your table need to be created with foreign key references for it to work. 您的表需要使用外键引用进行创建才能正常工作。 see sample below. 请参阅下面的示例。 I have tested it. 我已经测试过了

create table Employees(employee_No int primary key,Employee_name varchar(100));

create table Dependents(employee_No int primary key,dependent_name varchar(100), relationship varchar(100)
 foreign key (employee_No) references Employees(employee_No));

Insert for testing 插入进行测试

insert into Employees(employee_No,Employee_name) values(1558,'Bean');

insert into Employees(employee_No,Employee_name) values(1557,'Juliet');

insert into Dependents(employee_No,dependent_name,relationship) values(1558,'kevin','son');

code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = 'SELECT Employees.employee_No, Employees.Employee_name, Dependents.employee_No, Dependents.dependent_name, 
Dependents.relationship FROM Employees
LEFT JOIN Dependents ON Employees.employee_No = Dependents.employee_No
ORDER BY Employees.Employee_name';

    $result = mysqli_query($con,$query);
    while($row = mysqli_fetch_assoc($result)){ 
  $empno = $row['employee_No'];
  $empname = $row['Employee_name'];
  $relation = $row['relationship'];
 $dependant_name = $row['dependent_name'];

//you can now echo

echo $dependant_name.' '.$relation.'<br/>';
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM