mysql – 使用Propel 1.6从3个表中检索信息和计数的单个SQL查询
作者:互联网
我有以下(简化)数据库结构:
表书
id
title
表页面
id
bookId
number
表格
id
pageId
page.bookId和figure.pageId分别是指向主键book.id和page.id的外键.
一本书没有页面,页面也没有数字.
对于指定的书籍ID,使用单个sql查询,我想要检索
>书籍信息
>包含各自信息的页面列表
>每页的数字
结果的示例JSON表示如下:
{
"id": 34,
"title": "The title"
"pages": [
{
"id": "44",
"number": 1
"figureCount": 2
},
{
"id": "45",
"number": 2
"figureCount": 5
},
...
]
}
这可能与Propel 1.6和结果SQL查询应该是什么?
我使用MySql 5.0.
编辑:这是我的(简化)Propel schema.xml:
<table name="book" phpName="Book">
<column name="id" type="bigint" required="true" primaryKey="true" autoIncrement="true" />
<column name="title" type="varchar" size="512" required="true" />
</table>
<table name="page" phpName="Page" >
<column name="id" type="bigint" required="true" primaryKey="true" autoIncrement="true" />
<column name="book_id" type="bigint" required="true" />
<column name="number" type="integer" required="true" />
<foreign-key foreignTable="book" phpName="Book" refPhpName="Page" onUpdate = "cascade" onDelete = "cascade">
<reference local="book_id" foreign="id" />
</foreign-key>
</table>
<table name="figure" phpName="Figure">
<column name="id" type="bigint" required="true" primaryKey="true" autoIncrement="true" />
<column name="page_id" type="bigint" required="true" />
<foreign-key foreignTable="page" phpName="Page" refPhpName="Figure" onUpdate = "cascade" onDelete = "cascade">
<reference local="page_id" foreign="id"/>
</foreign-key>
</table>
解决方法:
根据@ user1073631的答案,推进查询应该是这样的:
$books = BookQuery::create()
->select(array('Book.Id', 'Book.Title', 'Page.Id', 'Page.Number'))
->withColumn('count(Figure.ID)', 'FigureCount')
->leftJoin('Book.Page')
->leftJoin('Page.Figure')
->groupBy('Book.Id')
->groupBy('Book.Title')
->groupBy('Page.Id')
->groupBy('Page.Number')
->find();
我不确定join()可能更好地看到你生成的类来确定这一点.
标签:propel,sql,mysql,join 来源: https://codeday.me/bug/20190725/1536057.html