Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select from one table, count from another where id's linked

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   
}

?>
like image 269
scarhand Avatar asked May 11 '11 22:05

scarhand


People also ask

How do I count data from another table in SQL?

You can use Common Table Expression(Cte) to write such query with readability. ;With CteFamily AS ( SELECT family_id FROM dbo. Families --WHERE --Put your conditions to filter family ), --get childrens count, with family id for selected family CteChildrenCount AS ( SELECT family_id , Count(*) As ChildrenCount FROM dbo.

Can we use count in where clause?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.

Does Count work with GROUP BY?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


1 Answers

Try changing the likes of...

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

...to...

(select count(*) from bookings where b.id_customer = c.id)
like image 170
Will A Avatar answered Sep 19 '22 17:09

Will A