SQL Query仅返回第一个客户的结果

时间:2016-12-05 09:48:16

标签: mysql

我的sql查询仅返回属于数据库中第一个客户的订单的结果。我哪里出错?

SELECT orders.id, 
       orders.created_at, 
       orders.customer_id, 
       customers.firstname, 
       customers.surname, 
       customers.email, 
       customers.telephone, 
       customer_addresses.address_1, 
       customer_addresses.address_2, 
       customer_addresses.address_2, 
       customer_addresses.city,
       customer_addresses.county, 
       customer_addresses.post_code 
FROM orders 
INNER JOIN customers ON orders.customer_id = customers.id 
INNER JOIN customer_addresses ON customers.id = customer_addresses.id 
ORDER BY orders.id 
LIMIT 0, 10;

2 个答案:

答案 0 :(得分:3)

如果您的所有客户都没有定义的地址,可能是原因,请尝试按如下方式更改JOIN运算符以进行测试。另外,删除最后的限制条件以确保您可以看到所有结果:

SELECT orders.id, 
       orders.created_at, 
       orders.customer_id, 
       customers.firstname, 
       customers.surname, 
       customers.email, 
       customers.telephone, 
       customer_addresses.address_1, 
       customer_addresses.address_2, 
       customer_addresses.address_2, 
       customer_addresses.city,
       customer_addresses.county, 
       customer_addresses.post_code 
FROM orders 
LEFT JOIN customers ON orders.customer_id = customers.id 
LEFT JOIN customer_addresses ON customers.id = customer_addresses.id 
ORDER BY orders.id;

答案 1 :(得分:1)

如果你回复@ ceyquem的答案中提到的所有客户都有address_id,我想你正在错误的列上加入customer_address表。它应该是

SELECT orders.id, 
       orders.created_at, 
       orders.customer_id, 
       customers.firstname, 
       customers.surname, 
       customers.email, 
       customers.telephone, 
       customer_addresses.address_1, 
       customer_addresses.address_2, 
       customer_addresses.address_2, 
       customer_addresses.city,
       customer_addresses.county, 
       customer_addresses.post_code 
FROM orders 
INNER JOIN customers ON orders.customer_id = customers.id 
INNER JOIN customer_addresses ON customers.address_id = customer_addresses.id 
ORDER BY orders.id 
LIMIT 0, 10;

希望它有效