选择所有客户和每个客户的总订单

时间:2014-11-06 13:41:43

标签: php mysql select join

对于每位客户,我想返回:ID,姓名,地址,城市,上限,国家和订单总数。表名是:客户(10条记录)和订单(20条记录)

我已经尝试过这段代码,但它不起作用

<?php
$conn = mysqli_connect('127.0.0.1','...','...','...') or die("Connection failed: " . $conn->connect_error);

$select = mysqli_query($conn,"SELECT customers.id,customers.name,customers.address,customers.city,customers.cap,customers.country COUNT(customerid) as TotalOrders FROM customers LEFT JOIN orders GROUP BY customer.id");

while($row = mysqli_fetch_array($select,MYSQLI_ASSOC))
{
    $tb = <<<table
    ...{$row['totalorders']}...
    table;
    echo $tb;
}
mysqli_free_result($select);

echo $num_record = mysqli_affected_rows($conn);

$conn->close();
?>

2 个答案:

答案 0 :(得分:1)

就像......

<?php
include('../path/to/connection/stateme.nts');

$query =
"
SELECT c.id
     , c.name
     , c.address
     , c.city
     , c.cap
     , c.country 
       COUNT(o.customerid) TotalOrders 
  FROM customers c
  LEFT 
  JOIN orders o
    ON o.customerid = c.id
 GROUP  
    BY c.id;
";


$result = mysqli_query($db,$query); ** where $db is something like mysqli_connect("myhost", "myusername", "mypassword");

while($row = mysqli_fetch_assoc($result))
{
$tb = <<<table
...{$row['totalorders']}...
table;
echo $tb;
}

mysqli_free_result($result);

echo $num_record = mysqli_affected_rows($db);

$db->close();
?>

(我没有php编码器)

答案 1 :(得分:0)

你的逗号丢失了 -

customers.country COUNT(customerid)
-----------------^

你遗漏了ON条件 -

FROM customers LEFT JOIN orders //ON would be here

您应该始终做的一件事是在中将这些查询放入代码之前,先针对数据库创建和运行查询。并始终总是包含错误检查。