简体   繁体   中英

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

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;

The problem is your datastructure: you are storing the list of authors as a comma-delimited list, which makes it harder to do basic operations such as joins. You should definitely fix your data model, by creating a junction table to represent the many-to-many relationship between books and authors, where each author/book tuple would be stored on a separate row. More about the whys and hows can be found in this famous SO answer .

That being said: for this specific question, you can join using MySQL string function find_in_set() , then aggregate:

select a.id, a.name, count(*) nb_books
from authors a
left join books b on find_in_set(a.id, b.author)
group by a.id, a.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM