2

父亲表

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 => ...
     ]

  ]
]

请你帮助我好吗?

笔记!一个父亲只能生一个孩子。

4

2 回答 2

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
于 2013-10-02T22:30:10.303 回答
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

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

于 2013-10-02T22:37:59.247 回答