从一个表中选择,从另一个 id 链接的表中计数
这是我的代码:
$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
}
?>
heres my code:
$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");
you can see what i am trying to do, but im not sure how to write this query properly.
heres the error i get:
Warning: mysql_fetch_assoc(): supplied
argument is not a valid MySQL result
resource
heres my 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
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试改变喜欢...
...到...
Try changing the likes of...
...to...
您的查询错误地使用了 COUNT,这已被 @Will A 的回答。
我还想建议一个可能更好的构造替代方案,我认为它反映了相同的逻辑:
注意:通常您应该将所有非聚合 SELECT 表达式包含到 GROUP BY 中。然而MySQL支持缩短的GROUP BY列表,所以指定唯一标识您正在提取的所有非聚合数据的键表达式就足够了。 请避免随意使用该功能。如果未包含在 GROUP BY 中的列每组有多个值,则您无法控制在不进行聚合拉出该列时实际返回哪个值。
Your query incorrectly uses COUNT, which has been covered by @Will A's answer.
I would also like to suggest a possibly better constructed alternative, which, I think, reflects the same logic:
Note: Normally you are expected to include all the non-aggregated SELECT expressions into GROUP BY. However MySQL supports shortened GROUP BY lists, so it's enough to specify the key expressions that uniquely identify all the non-aggregated data you are pulling. Please avoid using the feature arbitrarily. If a column not included in GROUP BY has more than one value per group, you have no control over which value will actually be returned when pulling that column without aggregation.