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

父と子 + 1 本だけを返します。しかし、子供が所有するすべての本を nPages でソートする必要があります。

このようなもの:

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

  ]
]

手伝っていただけませんか?

ノート!父親は子供を 1 人しか持てません。

4

2 に答える 2

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 に答える
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 に答える