2

当我尝试这段代码时:

$this->db->select('customers.customerid, customers.firstname');
$this->db->from('customers');

$this->db->join('orders', 'orders.customerid = customers.customerid');
$this->db->join('order_domains', 'order_domains.orderid = orders.orderid');
$this->db->join('order_hostings', 'order_hostings.orderid = orders.orderid');
$this->db->join('order_servers', 'order_servers.orderid = orders.orderid');


$this->db->group_by('orders.customerid');
$query = $this->db->get();

$domainusers = $query->result();
var_dump($domainusers);

我尝试过使用内部连接,但我尝试的一切仍然会返回一个空结果:

var_dump(); ---> array(0) { }

当我注释掉最后 3 个联接中的两个时:

//$this->db->join('order_hostings', 'order_hostings.orderid = orders.orderid');
//$this->db->join('order_servers', 'order_servers.orderid = orders.orderid');

它将返回结果:

var_dump(); ---> array(1) { [0]=> object(stdClass)#17 (1) { ["customerid"]=> string(1) "1" } }

我正在为这个项目使用codeigniter,有没有人知道为什么我使用多个连接后它会返回空结果?

4

4 回答 4

0

改变

$this->db->select('customers.customerid, customers.firstname');

$this->db->select('customers.*, orders.*, order_domains.*, order_hostings.*, order_servers.*');

如果之后您得到一些结果,请在 select 语句中仅保留每个连接表中所需的字段。

于 2013-06-21T09:27:25.093 回答
0

尝试将这两个更改为 LEFT OUTER JOIN。这样,如果这些表上没有匹配的记录,则不会阻止返回该行(在这种情况下,这些表中的字段将设置为 NULL)。

不太确定codeigniter,但认为它是这样做的: -

$this->db->select('customers.customerid, customers.firstname');
$this->db->from('customers');

$this->db->join('orders', 'orders.customerid = customers.customerid');
$this->db->join('order_domains', 'order_domains.orderid = orders.orderid');
$this->db->join('order_hostings', 'order_hostings.orderid = orders.orderid', 'left');
$this->db->join('order_servers', 'order_servers.orderid = orders.orderid', 'left');


$this->db->group_by('orders.customerid');
于 2013-06-21T10:56:39.820 回答
0

您可以在多个块中使用以下内容:

$this->db->distinct('orders.customerid');
$this->db->from('orders');

$this->db->join('order_domains', 'orders.orderid = order_domains.orderid', 'inner');
$this->db->join('customers', 'customers.customerid = orders.customerid');

$this->db->group_by('orders.customerid');
$query = $this->db->get();

$domainusers = $query->result();
var_dump($domainusers);
于 2013-06-21T14:12:00.017 回答
0

您可以运行$this->db->last_query();以查看运行的实际查询。在 MySQL 客户端中运行它并使用查询来弄清楚发生了什么通常很方便。

你也可以经常在 MySQL 中使用 EXPLAIN 来获取一些线索:

 EXPLAIN SELECT customers.customerid, customers.firstname
 FROM customers
 LEFT JOIN...

ETC...

于 2013-06-21T09:15:14.410 回答