sca*_*and 18 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");
Run Code Online (Sandbox Code Playgroud)
你可以看到我想要做什么,但我不知道如何正确编写这个查询.
继承人得到的错误:
警告: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
}
?>
Run Code Online (Sandbox Code Playgroud)
Wil*_*l A 36
尝试改变......的喜欢
count(select * from bookings where b.id_customer = c.id)
Run Code Online (Sandbox Code Playgroud)
...至...
(select count(*) from bookings where b.id_customer = c.id)
Run Code Online (Sandbox Code Playgroud)
And*_*y M 24
您的查询错误地使用了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
Run Code Online (Sandbox Code Playgroud)
注意:通常,您应该将所有非聚合的SELECT表达式包含在GROUP BY中.但是,MySQL支持缩短的GROUP BY列表,因此足以指定唯一标识您正在提取的所有非聚合数据的键表达式.请避免任意使用该功能.如果GROUP BY中未包含的列每个组具有多个值,则无法控制在不使用聚合的情况下拉动该列时实际返回的值.