在PHP mysql中循环两次

时间:2018-10-17 02:43:19

标签: php mysql loops mysqli

我需要一些帮助人员,我有两个桌子,

  1. 主管表(supervisor_id, name, area_specialty, branch)
  2. 任务表(t_id, no_task, supervisor_id)

我正在尝试制定一个查询,以使用给定的area of specialty和给定的branch过滤主管。

获取ID后,我需要在任务表中循环ID,以获取最少任务数(no_task)的一个ID。

下面是我尝试过的方法,但似乎无法获得正确的结果

$query2 = mysqli_query($connection, "SELECT * FROM supervisors WHERE area_specialty LIKE '%Embedded systems%' AND branch LIKE '%boston%'");
while($rows =mysqli_fetch_array($query2)) {
    $sid =$rows['supervisor_id'];

    $query1=mysqli_query($connection,"SELECT * from tasks INNER JOIN(select t_id, supervisor_id,MIN(no_task) AS nTask FROM tasks Group By supervisor_id) AS task_1  On task_1.t_id=task.t_id Where task_1.nTask=task.no_task");
    $rm = mysqli_fetch_array($query1);


}
echo $rm['supervisor_id'];

2 个答案:

答案 0 :(得分:0)

不确定在简单地在查询中使用一些内部联接时为什么要执行循环。当表很大并且正在循环这些查询和连接时,您将在以后遇到性能问题。没有太多细节,我会做这样的事情:

select * from supervisor_table as s
  inner join tasks_table as t
  on t.supervisor_id = s.supervisor_id
  where s.area_specialty like '%Embedded systems%' AND s.branch like '%boston%';

答案 1 :(得分:0)

查询将根据您的要求提供任务列表:

SELECT t.* FROM task AS t
INNER JOIN (
   SELECT MIN(no_task) AS MinTask FROM tasks Group By supervisor_id 
   INNER JOIN  supervisor_table AS s ON t.supervisor_id = s.supervisor_id
   WHERE area_specialty LIKE '%Embedded systems%' AND branch LIKE '%boston%'
) as Task1 ON Task1.MinTask = t.no_task

对于具有给定区域专业和分支的主管,联接中的子查询将获得最少的任务数。