繁体   English   中英

使用PHP和SQL进行多次连接没有结果

[英]No result on multiple join with PHP and SQL

当我尝试此代码时:

$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,有人知道我一旦使用多个联接为什么会返回空结果?

您可以运行$this->db->last_query(); 查看实际运行的查询。 在MySQL客户端中运行它并处理查询以了解发生的情况通常很方便。

您还可以经常在MySQL中使用EXPLAIN以获得一些线索:

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

等等...

更改

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

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

如果之后得到一些结果,请仅将EACH联接表中所需的字段保留在select语句中。

尝试将这两个更改为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');

您可以在多个块中使用以下代码:

$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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM