开发者

MySQL JOIN based on sortorder field

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜