从多个表中获取行 - PHP和循环

时间:2017-12-07 04:21:10

标签: php sql

我试图从2个表中搜索子类别的所有父类别

示例数据库

AsyncTask

如果我搜索' Utensils',希望得到

分类:

  • 炊具
  • 厨房
  • 产品

结果,但我对SQL有点困惑。

notifyDataSetChanged()

我没有从此代码中获得任何结果或错误

2 个答案:

答案 0 :(得分:0)

要重复访问同一个表,最好使用存储过程。

## Create a view so that we can work more easily with the tables 

create view items as select Categ_name as name, Categ_parent as parent from table1
  union (select Temp_name as name, Temp_parent as parent from table2);

name            parent
-------------------------
Item            0
House           Item
Car             Item
Kitchen         House
Living Room     House
Appliance       Living Room
Cookware        Kitchen
Utensils        Cookware

DROP PROCEDURE IF EXISTS selectName;
CREATE PROCEDURE selectName(IN currentName VARCHAR(100))
BEGIN
  drop temporary table if exists tmp_results;
  create temporary table tmp_results (
    name varchar(100)
  );

  while (exists(select parent from items where name = currentName)) DO
    select parent into currentName from items where name = currentName;
    insert into tmp_results select currentName;
  END WHILE;

  select * from tmp_results;
END;

要使用此程序:

call selectName('Utensils');

Cookware
Kitchen
House
Item
0

用于初始化数据库的PHP代码(仅运行语句ONCE以创建视图和存储过程):

// create view
$mysqli->query("
  drop view if exists viewItems;
  create view viewItems as select Categ_name as name, Categ_parent as parent from table1
    union (select Temp_name as name, Temp_parent as parent from table2)";
");

// create stored procedure
$mysqli->query("
  DROP PROCEDURE IF EXISTS selectParents;
  CREATE PROCEDURE selectParents(IN currentName VARCHAR(100))
  BEGIN
    drop temporary table if exists tmp_results;
    create temporary table tmp_results (
      name varchar(100)
    );

    while (exists(select parent from viewItems where name = currentName)) DO
      select parent into currentName from viewItems where name = currentName;
      insert into tmp_results select currentName;
    END WHILE;

    select * from tmp_results;
  END"
);

要查询的PHP代码

$name = mysqli_real_escape_string($name);
$results = $mysqli->query("CALL selectParents($name)");

答案 1 :(得分:0)

首先,您编写的SQL在“from ...”之前有一个错误,即“,”。

我建议使用UNION而不是当前的SQL命令。当前命令将混合两个父值,其中一个可能不正确。

尝试使用以下解决方案,该解决方案在我的计算机上运行良好:

$i='Utensils';


while($i!='0'){

$sql="(SELECT Categ_parent as parent from table1 WHERE Categ_name='".$i."')
        UNION
        (SELECT  Temp_parent as parent from table2 where Temp_name='".$i."')";


$result = mysqli_query($con,$sql);
if($result && mysqli_num_rows($result)){
    $row = mysqli_fetch_array($result);
    $i = $row["parent"];
}
else{
    $i = '0';
}

echo $i."<br>";
}