I have two tables, author and quote:
author: AID, Name, YOB, YOD.
quote: ID, AuthID, Content.
I currently get all the authors with one query and as I loop through them, I run a second query to get the count of quotes that have the current AID:

$sql = "SELECT AID, Name FROM author order by Name";
        if (!$res = $this->conn->query($sql)){
            echo $this->conn->error; die();
        } else {
            while($row = $res->fetch_assoc()){
                $count_sql = "select count(*) as count from quote where AuthID='".$row['AID']."'";
                if (!$count_res = $this->conn->query($count_sql)){
                echo $this->conn->error; die();
                } else {
                    $count_row = $count_res->fetch_assoc();
                    $row['count'] = $count_row['count'];
                }

Is it possible to collect the counts in a single query?
"SELECT AID, Name from author and count(AuthID=AID from quotes)"
I have seen talk of 'HAVING', 'IN' and other keywords, but can't find a comprehensible answer.

Recommended Answers

All 5 Replies

Something like this:

SELECT a.AID, a.Name, COUNT(*) AS QuoteCount
FROM author a
LEFT JOIN quote q ON a.AID = q .AuthID
GROUP BY a.AID
ORDER BY a.Name

It's perfect thank you Pritaeas. I find it so difficult to visualise the table joins and relationships, I really need to spend some time on it to get my head around it.

I will spend some time with those links, thanks again :D

Do some practice on ms access query design, it might help you a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.