[英]select from one table, count from another where id's linked
继承我的代码:
$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
}
?>
尝试改变......的喜欢
count(select * from bookings where b.id_customer = c.id)
...至...
(select count(*) from bookings where b.id_customer = c.id)
您的查询错误地使用了COUNT,这已被@Will A的回答所涵盖。
我还想建议一个可能更好的构造替代方案,我认为这反映了相同的逻辑:
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支持缩短的GROUP BY列表 ,因此足以指定唯一标识您正在提取的所有非聚合数据的关键表达式。 请避免任意使用该功能 。 如果GROUP BY中未包含的列每个组具有多个值, 则无法控制在不使用聚合的情况下拉动该列时实际返回的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.