从一个表中选择,从id链接的另一个表中计数

时间:2011-05-11 22:03:44

标签: mysql sql select join

继承我的代码:

$sql = mysql_query("select c.name, c.address, c.postcode, c.dob, c.mobile, c.email, 
                    count(select * from bookings where b.id_customer = c.id) as purchased, count(select * from bookings where b.the_date > $now) as remaining, 
                    from customers as c, bookings as b 
                    where b.id_customer = c.id
                    order by c.name asc");

你可以看到我想要做什么,但我不确定如何正确地编写这个查询。

这是我得到的错误:

  

警告:mysql_fetch_assoc():提供   参数不是有效的MySQL结果   资源

继承我的mysql_fetch_assoc:

<?php

while ($row = mysql_fetch_assoc($sql))
{
    ?>

    <tr>
    <td><?php echo $row['name']; ?></td>
    <td><?php echo $row['mobile']; ?></td>
    <td><?php echo $row['email']; ?></td>
    <td><?php echo $row['purchased']; ?></td>
    <td><?php echo $row['remaining']; ?></td>
    </tr>

    <?php   
}

?>

2 个答案:

答案 0 :(得分:36)

尝试更改...的喜欢

count(select * from bookings where b.id_customer = c.id)

...到...

(select count(*) from bookings where b.id_customer = c.id)

答案 1 :(得分:23)

您的查询错误地使用了@Will A's answer已涵盖的COUNT。

我还想建议一个可能更好的构造替代方案,我认为这反映了相同的逻辑:

SELECT
  c.name,
  c.address,
  c.postcode,
  c.dob,
  c.mobile,
  c.email,
  COUNT(*) AS purchased,
  COUNT(b.the_date > $now OR NULL) AS remaining
FROM customers AS c
  INNER JOIN bookings AS b ON b.id_customer = c.id
GROUP BY c.id
ORDER BY c.name ASC

注意:通常,您应该将所有非聚合SELECT表达式包含在GROUP BY中。但是,MySQL支持shortened GROUP BY lists,因此足以指定唯一标识您正在提取的所有非聚合数据的关键表达式。 请避免任意使用此功能。如果未包含在GROUP BY中的列每个组都有多个值,那么您无法控制在拉出没有聚合列时实际返回的值。

相关问题