位置跟踪系统中的单个查询

时间:2014-10-27 01:25:15

标签: php mysql nested-loops

我有这个系统可以跟踪物品的位置。

示例表:

constb

consid cons
  1    Nint
  2    PS
  3    XB
  4    AT

consloctb

locid  consid  loc
  1       1     GS
  2       2     IT
  3       2     GG
  4       1     IG
  5       2     SS
  6       3     SM
  7       3     FB
  8       1     SS
  9       2     SM
  10      3     IT
  11      4     SM

结果将显示所有项目的当前位置。它看起来像这样:

Nint - SS
PS - SM
XB - IT

我现在想的逻辑是做一个嵌套循环。

$res=mysqli_query($con,"SELECT * FROM constb ORDER BY id");

while($row=mysqli_fetch_array($res)){

  $consid=$row["consid"];

  $res2=mysqli_query($con,"SELECT * FROM consloctb WHERE consid='$consid' ORDER BY locid DESC LIMIT 1");

  while($row2=mysqli_fetch_array($res2)){

    echo $row["cons"]." - ".$row2["loc"];

  } /* END OF SECOND LOOP */

} /* END OF FIRST LOOP */

这将显示我想要的结果。

如果我添加一个搜索功能,我会做同样的嵌套循环过程,如果搜索到的位置与loc列相同,则会在第二个循环中添加另一个WHERE条件。

$srchloc=$_POST["search"]; /* DATA SUBMITTED */

$res=mysqli_query($con,"SELECT * FROM constb ORDER BY id");

while($row=mysqli_fetch_array($res)){

  $consid=$row["consid"];

  $res2=mysqli_query($con,"SELECT * FROM consloctb WHERE consid='$consid' AND loc='$srchloc' ORDER BY locid DESC LIMIT 1");

  while($row2=mysqli_fetch_array($res2)){

    echo $row["cons"]." - ".$row2["loc"];

  } /* END OF SECOND LOOP */

} /* END OF FIRST LOOP */

搜索示例,如果用户搜索当前位于SM的项目,结果会显示

PS - SM
AT - SM

我认为做第二个选项可能会减慢搜索过程。如何使用单个查询实现此目的?或者让这个过程更快?

1 个答案:

答案 0 :(得分:1)

如果您要列出所有项目的当前位置:

SELECT t.cons,
       t.loc
FROM
  (SELECT constb.consid AS id,
          constb.cons AS cons,
          consloctb.loc AS loc
   FROM constb
   LEFT JOIN consloctb ON constb.consid = consloctb.consid
   ORDER BY constb.consid,
            consloctb.locid DESC) AS t
GROUP BY t.id;

如果您希望为搜索位置过滤结果,则可以添加HAVING子句:

SELECT t.cons,
       t.loc
FROM
  (SELECT constb.consid AS id,
          constb.cons AS cons,
          consloctb.loc AS loc
   FROM constb
   LEFT JOIN consloctb ON constb.consid = consloctb.consid
   ORDER BY constb.consid,
            consloctb.locid DESC) AS t
GROUP BY t.id HAVING t.loc='SM';