Skip to content
Advertisement

Select from a table and count from another

i have two tables, one for authors the other for books, i want to count the number of books per author

Table authors 
+----+-------------------+
|id  | name              |
+----+-------------------+
|1   | PROF. H.D IBRAHIM |
+----+-------------------+
|2   |DR. M.L BUGA       |
--------------------------
Table books
+--+-------------+------------+
|id|name         | author     |
+--+-------------+------------+
|1 |Sabitol      | 1          |
+--+-------------+------------+
|2 | Garlic      | 2,1        |
+--+-------------+------------+
|3 |Gold         | 2          |
+--+-------------+------------+

I used the sql query:

SELECT authors.id,authors.name, COUNT(books.author) As num 
FROM `authors` 
LEFT JOIN books ON authors.id=books.author 
GROUP BY authors.id;

The query returns 1 for first author instead of 2

Advertisement

Answer

Use FIND_IN_SET()

SELECT
    authors.id,authors.name, COUNT(books.author) As num 
FROM authors
     INNER JOIN books
ON 
    FIND_IN_SET(authors.id,books.author)
GROUP BY 
    authors.id;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement