【问题标题】:select from one table, count from another where id's linked从一个表中选择,从另一个 id 链接的表中计数
【发布时间】:2011-08-23 16:34:48
【问题描述】:

这是我的代码:

$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   
}

?>

【问题讨论】:

  • 从 phpmyadmin 或 CLI 界面执行时是否有效?
  • 请说明您是如何完成mysql_fetch_assoc() 查询的。
  • 我已将其添加到原帖中...

标签: mysql sql select join


【解决方案1】:

尝试改变...

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

...到...

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

【讨论】:

    【解决方案2】:

    您的查询错误地使用了 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 BY 中。但是 MySQL 支持shortened GROUP BY lists,因此指定唯一标识您要提取的所有非聚合数据的键表达式就足够了。 请避免随意使用该功能。如果未包含在 GROUP BY 中的列在每个组中具有多个值,则您无法控制在拉出该列不进行聚合时实际返回哪个值。。 p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 2014-06-12
      • 1970-01-01
      • 2015-04-10
      • 2018-03-09
      相关资源
      最近更新 更多