选择父亲+他的孩子+儿童书籍按nPages排序

时间:2013-10-02 22:20:05

标签: mysql database left-join

父亲表

id     name    age    married
9      Max     45     1

儿童桌

id    father_id    name 
12       9         Rose

书籍表

id    owner_id   title            nPages
1        12       Harry potter    755
2        12       JDK             124

我试过

Select father.*, child.*, books.*
FROM fathers father
LEFT JOIN children child
    ON child.father_id = father.id
LEFT JOIN books book
    ON book.owner_id = child.id
WHERE father.married = 1
LIMIT 1

返回父亲和孩子+ 只有一本书。但我需要孩子拥有的所有书籍按nPages排序。

这样的事情:

[
  name : MAX , 
  age : 45, 
  married : 1, 
  child => [
     father_id => 9, 
     name => Rose, 
     books => [
        book1 => ..., 
        book2 => ...
     ]

  ]
]

你能帮我吗?

请注意!一个父亲只能生一个孩子。

2 个答案:

答案 0 :(得分:2)

你有没有试过这样的事情......

SELECT
    father.name AS fatherName,
    child.name AS childName,
    COUNT(books.owner_id) AS bookCount
FROM
    books
    INNER JOIN child ON books.owner_id = child.id
    INNER JOIN father ON child.father_id = father.id
GROUP BY
    books.owner_id
ORDER BY
    bookCount DESC
LIMIT 1

更新(未选中)

SELECT
    father.name AS fatherName,
    child.name AS childName,
    books.title AS bookName,
    books.nPages AS pageCount
FROM
    books
    INNER JOIN child ON books.owner_id = child.id
    INNER JOIN father ON child.father_id = father.id
WHERE 
    books.id IN
                (
                    SELECT
                          books.id
                    FROM 
                          books
                    GROUP BY
                          books.owner_id
                    ORDER BY
                          COUNT(books.owner_id) DESC
                    LIMIT 1
                )
ORDER BY
    books.nPages DESC

最终更新(未选中)

SELECT
    father.name AS fatherName,
    child.name AS childName,
    books.title AS bookName,
    books.nPages AS pageCount
FROM
    child
    INNER JOIN father ON child.father_id = father.id
    INNER JOIN books ON books.owner_id = child.id
WHERE 
    child.id IN
                (
                    SELECT
                          books.owner_id
                    FROM 
                          books
                    GROUP BY
                          books.owner_id
                    ORDER BY
                          COUNT(books.owner_id) DESC
                    LIMIT 1
                )
ORDER BY
    books.nPages DESC

答案 1 :(得分:2)

我只是不记得MySQL是否允许你为IN条款添加限制......但是你让我知道:

SELECT f.*, b.*, c.* FROM books b
JOIN children c ON b.owner_id = c.id
JOIN fathers f ON c.father_id = f.id
WHERE c.id in (
    SELECT owner_id from books
    GROUP BY owner_id
    ORDER BY count(*) DESC
    LIMIT 1
)
ORDER BY b.nPages

这适用于任何数量的孩子。