开发者

MySQL JOIN based on sortorder field

开发者 https://www.devze.com 2023-03-29 00:47 出处:网络
I have a database with several users that each can have several books. I want to get a list of users and their first book based on the (Integer) sortorder field in the table book.

I have a database with several users that each can have several books.

I want to get a list of users and their first book based on the (Integer) sortorder field in the table book.

Below is a example of the SQL I use now. Only problem is that it does not return the first book based on the sortorder field for each user.

SELECT
    b.id, b.user_id, b.sortorder, b.title
FROM
    books AS b
JOIN
    books_categories AS bc
ON
    (b.id =  bc.book_id)
JOIN
    categories AS c
ON
    (c.id =  bc.category_id)
JOIN
    users AS u
ON
    (u.id =  b.user_id)
GROUP BY
    b.u开发者_开发技巧ser_id


You need to join to a subquery that selects the first book for each user.

SELECT b.id, b.user_id, b.sortorder, b.title
FROM books b
JOIN (
    SELECT b2.user_id, min(b2.sortorder) sortorder
    FROM books b2
    GROUP BY b2.user_id
) first_books USING (user_id, sortorder); 
0

精彩评论

暂无评论...
验证码 换一张
取 消