2011-05-11 70 views
12

继承人我的代码:从一个表中选择,从另算其中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 
} 

?> 
+0

从phpmyadmin或CLI界面执行时,这是否工作? – 2011-05-11 22:07:01

+0

请说明你如何做了你的'mysql_fetch_assoc()'查询。 – stealthyninja 2011-05-11 22:07:23

+1

我将它添加到原帖... – scarhand 2011-05-11 22:09:13

回答

28

尝试改变喜欢...

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

...到...

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

您的查询不正确地使用COUNT,它已经覆盖@Will A's answer

我也想提出一个可能更好的构建替代,我想它,反映了相同的逻辑:

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通过。但是,MySQL支持shortened GROUP BY lists,因此只需指定唯一标识所有正在提取的非聚合数据的关键表达式即可。 请避免使用此功能任意。如果未包含在GROUP BY中的列的每个组有多个值,则您无法控制,在拉动该列而没有汇总时,实际上将返回该值。

+0

这应该是正确的答案。 – jaypabs 2017-03-16 00:50:28

相关问题