写Mysql左连接不起作用?

时间:2014-09-21 17:38:52

标签: mysql left-join

我有这张桌子

制品

articles_id

ARTICLE_NAME
article_qty
article_price
article_amount

订单

orders_id
article_id的
INVOICE_ID
CUSTOMER_ID

客户

customers_id
CUSTOMER_NAME
customer_position
customer_office

customer_invoice

当我做这样的事情时

$sql="SELECT customer_name, article_name FROM orders LEFT JOIN articles ON article_id = articles_id LEFT JOIN customers on customer_id = customers_id";

它没有得到任何结果,在一个查询中将这两个表连接起来的正确方法是什么?

我使用CI 喜欢这个

$this->db->query($sql);

我得到了什么

object(CI_DB_mysql_result)#28 (8) { ["conn_id"]=> resource(31) of type (mysql link persistent) ["result_id"]=> resource(52) of type (mysql result) ["result_array"]=> array(0) { } ["result_object"]=> array(0) { } ["custom_result_object"]=> array(0) { } ["current_row"]=> int(0) ["num_rows"]=> int(2) ["row_data"]=> NULL } 

1 个答案:

答案 0 :(得分:1)

您需要为您使用的任何表连接指定别名:

$sql="SELECT c.customer_name, a.article_name FROM orders o 
LEFT JOIN articles a ON o.article_id = a.articles_id 
LEFT JOIN customers c on o.customer_id = c.customers_id";

或者你可以使用这样的USING语法:

$sql="SELECT c.customer_name, a.article_name FROM orders o 
LEFT JOIN articles a ON USING(articles_id) 
LEFT JOIN customers c on USING(customer_id);