使用mysql JOIN获取重复数据

时间:2018-03-07 18:12:37

标签: php mysql

我使用JOIN查询了5个表但是我获取了每个记录的重复数据我获得了8行相同的数据。 这是我的代码

          <?php
    include("dbconnection.php");
      $list = "SELECT user.user_id,user.empid,personal.fname,employment.position,employment.dep,educational.level,contact.phone_one,contact.phone_relation_one
       FROM user JOIN personal JOIN employment JOIN contact JOIN educational
          ON  (personal.empid_personal=user.empid = employment.empid_emp = contact.empid_contact)";
      $result = mysqli_query($con,$list);

      while($row = mysqli_fetch_assoc($result)){
        echo "<tr>";
        echo    "<td>".$row['user_id']."</td>";
        echo    "<td>".$row['empid']."</td>";
        echo    "<td>".$row['fname']."</td>";
        echo     "<td>".$row['position']."</td>";
        echo     "<td>".$row['dep']."</td>";
        echo     "<td>".$row['level']."</td>";
        echo    "<td>".$row['phone_one']."</td>";
        echo    "<td>" .$row['phone_relation_one']."</td>";
        echo   '<td class="text-center"><a class="btn btn-info btn-xs" href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>';
        echo "</tr> ";

      }
       ?>
             </table>

1 个答案:

答案 0 :(得分:2)

你的SQL应该更像......

  $list = "SELECT user.user_id,user.empid,personal.fname,employment.position,employment.dep,educational.level,contact.phone_one,contact.phone_relation_one
   FROM user 
   JOIN personal ON personal.empid_personal=user.empid
   JOIN employment ON  user.empid = employment.empid_emp
   JOIN contact ON user.empid = contact.empid_contact
   JOIN educational ON ?????";

这会将每个连接表链接到主表(无论如何都是这种情况)。

educational表也应该有某种链接,但是你没有列出这个。这也可能是重复项可以进入的地方,链接到表没有任何条件如何匹配数据,也称为CROSS JOIN。