2013-03-22 88 views
0

为减少查询的次数,当我选择从我的数据库的东西,我想推出最好的一个,它可以是其中之一:如何在两个或多个实例之间共享JOIN的结果?

1- SELECT ... FROM cities JOIN states ON city.stateID = state.stateID WHERE city.cityID = ... 
2- SELECT ... FROM cities WHERE city.cityID = ... 
3- SELECT ... FROM states WHERE state.stateID = ... 

如果我执行的第一个,我不需要(可能)执行第二次都没有第三个查询,因为我已经有了数据。

但我怎样才能分享两个或更多类实例之间的单个连接查询的结果? 假设我必须首先使用第三个查询,因为我已经拥有3个数据,您将如何从代码中控制City实例的创建?

<?php 

class City 
{ 
     protected $state; 

     function getState() 
     { 
      if(!$this->state) 
       $this->state = State::getByID($this->stateID); 
      return $this->state; 
     } 

     // since i may already have (in the outer scope) the $state instance... 
     // to avoid an unnecessary query (State::getByID()) i allow to set the state: 
     function setState(State $state) 
     { 
      if($state->stateID == $this->stateID) 
       $this->state = $state; 
      else 
       throw new Exception("This City doesn't belong to the given State"); 
     } 
} 

这是正确的吗?我做对了吗?

例如,我可以创建“地址”像这样的构造:

<?php 

class Address 
{ 
    const PREFETCH_CITY = 1; 
    const PREFETCH_STATE = 2; 
    const PREFETCH_ALL = 3; 

    construct($cityID, $prefetch = 0) 
    { 
     if($prefetch & static::PREFETCH_CITY) 
       // i use the "JOIN cities" query (i also set $this->city) 
     elseif($prefetch & static::PREFETCH_STATE) 
       // i use the "JOIN states" query (i also set $this->state) 
     elseif($prefetch & static::PREFETCH_ALL) 
       // i use the "JOIN states JOIN cities" query 
       // (i preset also both $this->city and $this->state) 
     else 
       // i don't use any JOIN, i just get the city 
    } 
} 

其实现在我想,构造应该是在一个单独的类,但无论...

总的来说......我可以读些关于这个论点的文章吗?书籍,教程,欢迎

希望已经明确,我的英语很糟糕......非常感谢你提前:)

+0

不知道PHP我不会试图回答这个问题,但它听起来像你需要的是某种智能缓存你的结果。但是我不知道PHP生命周期是如何工作的,所以我甚至不知道如何开始告诉你如何在PHP中实现类似的东西,或者即使PHP本身可以实现。 – Pete 2013-03-22 21:24:20

+0

这实际上并不涉及到PHP,我也使用其他语言,所以我正在寻找一个通用的方法来解决这个问题 – skyline26 2013-03-22 21:26:58

+0

您可能想描述一下您的整体架构,否则很难给出超出一般想法的建议。 – Pete 2013-03-22 21:28:36

回答

0

是否有过这样的情况:Address类将被称为都市类将没有被叫过?如果没有,那么你可以使用Address类扩展City类,你可以在Address类中访问City类的变量,所以只需改变它即可。然后,City类从数据库中获取信息并将其分配给各种变量,然后可以从Address类访问它们。

class Address extends City {