如何将两个表数据转换为单列?

时间:2017-11-20 14:56:00

标签: php mysql

我有两张表emp_attendance和emp_leave。

emp_attendance:

id    date_in
200   2015-05-22
200   2015-05-23

emp_leave:

id    date_leave   status
200   2015-05-24    sick

如何获得以下输出?

 id     date          status
 200  2015-05-22
 200  2015-05-23
 200  2015-05-24       sick

我尝试了以下的SQL查询。但我无法获得预期的结果。

$query1 = "SELECT * FROM emp_attendance e INNER JOIN emp_leave a ON e.id=a.eid  WHERE AND MONTH(e.date_in)='$monthSearch' AND YEAR(e.date_in)='$yearSearch'";

$employees = mysqli_query($connection,$query1);
    while ($i = mysqli_fetch_array($employees)) {
         echo "<tr>";
         echo "<td>".$i['date_in']."</td>";
         echo "<td>".$i['status']."</td>";
         echo "</tr>";
     }

1 个答案:

答案 0 :(得分:3)

在mySQL中使用UNION来组合来自两个结构相似的表的数据。

(SELECT `id`, `date_in` AS `date`, '' AS `status` FROM `emp_attendance`)
UNION ALL
(SELECT `id`, `date_leave` AS `date`, `status` FROM `emp_leave`)
ORDER BY `date`

然后您可以使用PHP访问数据:

$employees = mysqli_query($connection,$query1);
while ($i = mysqli_fetch_array($employees)) {
     echo "<tr>";
     echo "<td>".$i['date']."</td>";
     echo "<td>".$i['status']."</td>";
     echo "</tr>";
 }