如果搜索到表A的结果为零,如何搜索表B.

时间:2016-03-14 11:52:21

标签: php mysql performance pdo

我有三个表,我需要在第一个表中搜索,它没有任何结果,然后搜索到第二个表,依此类推......!

这是我的代码:

// connecting to database
$stm1 = $this->dbh->prepare(" select * from table1 where col = :name; ");
$stm1->bindValue(":name", $name, PDO::PARAM_STR);
$stm1->execute();
$which_table = "table1";

// the result of searching into table1 is zero, then search into table2
if (!$stm1->rowCount()) {
    $stm2 = $this->dbh->prepare(" select * from table2 where col = :name; ");
    $stm2->bindValue(":name", $name, PDO::PARAM_STR);
    $stm2->execute();
    $which_table = "table2";

    // the result of searching into table2 is zero, then search into table3
    if (!$stm2->rowCount()) {
        $stm3 = $this->dbh->prepare(" select * from table3 where col = :name; ");
        $stm3->bindValue(":name", $name, PDO::PARAM_STR);
        $stm3->execute();
        $which_table = "table3";

        // the result of searching into table3 is also zero
        if (!$stm3->rowCount()) {
            $which_table = 'none of them';
        }
    }
}

我的代码也可以运行,但它很慢,我如何优化它并使其更快?如您所见,有三个独立的查询和多个if语句..如何减少它们?一般来说,我如何改进该代码?我可以使用pure-sql吗?

2 个答案:

答案 0 :(得分:1)

  

我的代码也可以运行,但它很慢,我如何优化它并使其更快?

为列col

添加索引

顺便说一句,您可以在查询中添加limit 1。它会帮助你在表格中有数以万计的值来匹配

答案 1 :(得分:1)

如果您的代码很慢,那么您可能只需要索引:

create index idx_table1_col on table1(col);
create index idx_table2_col on table2(col);
create index idx_table3_col on table3(col);

使用索引,您还可以将查询短语作为单个语句,假设表中的列相同:

select t1.*
from table1 t1
where t1.col = :name
union all
select t2.*
from table2 t2
where t2.col = :name and
      not exists (select 1 from table1 t1 where t1.col = :name)
union all
select t3.*
from table3 t3
where t3.col = :name and
      not exists (select 1 from table1 t1 where t1.col = :name) and
      not exists (select 1 from table2 t2 where t2.col = :name);

这是一个更复杂的查询,但您的代码只需要一个查询。并且,对于索引,它应该非常快。