内部联接不起作用

时间:2011-03-26 04:07:40

标签: php mysql sql

大家好,请帮我解决这个从四个表中获取数据的问题。这是编写查询的正确方法吗

SELECT task.employee_id , task.user_id , task.service_id from task 
INNER JOIN employee  employee.name , employee.pic ON employee.pno =employee_id 
INNER JOIN user  user.name , user.pic ON user.pno = user_id 
INNER JOIN service  service.name , service.description ON service.service_id =service_id";

当我获取数据时我将如何显示它们$ a = $ data ['id'];

及其出现错误

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,

现在我已更新到此

function viewAll()
{


$this->query = "SELECT task.employee_id , task.user_id , task.service_id, employee.name , employee.pic, user.name , user.pic, service.name , service.description
FROM task  INNER JOIN employee  ON employee.pno = task.employee_id  INNER JOIN user  ON user.pno = employee.user_id  INNER JOIN service  ON service.service_id = user.service_id;";



$rd = $this->executeQuery();
$recordsArray = array(); // create a variable to hold the informationm
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row; // add the row in to the results (data) array
}

我收到此错误

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,

2 个答案:

答案 0 :(得分:1)

不,这不正确。

SELECT task.employee_id , task.user_id , task.service_id, employee.name , employee.pic, user.name , user.pic, service.name , service.description
FROM
    task 
    INNER JOIN employee  ON employee.pno = task.employee_id 
    INNER JOIN user  ON user.pno = employee.user_id 
    INNER JOIN service  ON service.service_id = user.service_id;

我不能告诉你它应该是什么,但应该更接近。我根据原始查询对你的连接和列名做了最好的猜测。您想要“查看”的所有字段都必须位于SELECT子句中。当你加入另一张桌子时,你需要解释如何。例如,您从task加入employee,因此我假设task有一个名为emmployee_id(或类似)的列,这是您需要加入的字段。

答案 1 :(得分:1)

您的查询应该类似于:

SELECT t.employee_id, 
       t.user_id, 
       t.service_id 
  FROM TASK t
  JOIN EMPLOYEE e ON e.pno = t.employee_id 
  JOIN USER u ON u.pno = t.user_id 
  JOIN SERVICE s ON s.service_id = t.service_id

但是对于您的查询,存在重复行的风险,因为EPLLOYEE,USER和SERVICE的JOIN在所有这些行中都有相关记录,或者其中一个表具有多个相关子记录。使用:

SELECT DISTINCT
       t.employee_id, 
       t.user_id, 
       t.service_id 
  FROM TASK t
  JOIN EMPLOYEE e ON e.pno = t.employee_id 
  JOIN USER u ON u.pno = t.user_id 
  JOIN SERVICE s ON s.service_id = t.service_id

不使用DISTINCT(或GROUP BY)编写查询的另一种方法是:

SELECT t.employee_id, 
       t.user_id, 
       t.service_id 
  FROM TASK t
 WHERE EXISTS (SELECT NULL FROM EMPLOYEE e WHERE e.pno = t.employee_id)
   AND EXISTS (SELECT NULL FROM USER u WHERE u.pno = t.user_id)
   AND EXISTS (SELECT NULL FROM SERVICE s WHERE s.service_id = t.service_id)

当我获取数据时我将如何$a = $data['id'];

显示它们

使用PHP代码中的列名或列别名(如果已定义)来获取适当的值:

$a = $data['employee_id'];
$b = $data['user_id'];
$c = $data['service_id'];