[英]MySQL: standard approach VS set-based approach for multi-row results
Following up on this question , there is problem with the standard approach or a recursive approach in the case below. 跟踪此问题 ,在以下情况下,标准方法或递归方法存在问题。
For instance, I want to return the page with the same parent_id
and some pages have multiple row contents , 例如,我想返回具有相同
parent_id
的页面,并且某些页面具有多个行内容 ,
page
table page
表
page_id page_title parent_id
1 a 1
2 aa 1
3 ab 1
4 ac 1
content
table content
表
content_id content_text
1 text one
2 text two
3 text one aa
4 text two aa
5 text one ab
6 text one ac
content structure
table content structure
表
page_id content_id order_in_page
1 1 1
1 2 2
2 3 1
2 4 2
3 5 1
4 6 1
The standard approach, 标准方法
SELECT
p.*,
c.*,
x.*
FROM pages AS p
LEFT JOIN pages_structures AS x
ON x.page_id = p.page_id
LEFT JOIN pages_contents AS c
ON c.content_id = x.content_id
WHERE p.parent_id = '1'
AND p.page_id != '1'
result (it lists the row as 4 items), 结果(将行列为4项),
page_id page_title parent_id content_text order_in_page
2 aa 1 text one aa 1
2 aa 1 text two aa 2
3 ab 1 text one ab 1
4 ac 1 text one ac 1
As you can notice that there are two rows with page_id 2
and one row for each 3
and 4
. 如您
page_id 2
,有两行具有page_id 2
, 每行 3
和4
。 How do you display the data into HTML with the standard approach like below (as suggested in one of the answer in the previous question )? 你怎么用像下面的标准的方法显示数据转换成HTML(如前面在回答一个提示问题 )?
echo $page[0]['page_title'];
echo $page[0]['content_text'];
But with set-based one, I can do it with this, 但是使用基于集合的方法 ,我可以做到这一点,
SELECT
page_id,
page_title,
MAX(IF(order_in_page = 1, content_text, NULL)) AS content_1,
MAX(IF(order_in_page = 2, content_text, NULL)) AS content_2,
.
.
.
FROM
pages AS p LEFT JOIN
pages_structures AS x ON x.page_id = p.page_id LEFT JOIN
pages_contents AS c ON c.content_id = x.content_id
WHERE
p.parent_id = '1'
AND
p.page_id != '1'
GROUP BY page_id
in PHP, 在PHP中,
foreach($items as $item)
{
echo '<li><h3>'.$item['page_title'].'</h3>';
echo '<p>'.$item['content_1'].'</p>';
echo '<p>'.$item['content_2'].'</p></li>';
}
the HTML (it lists the row as 3 items which is correct), HTML(将该行列为3个正确的项),
<li>
<h3>aa</h3>
<p>text one aa</p>
<p>text two aa</p>
</li>
<li>
<h3>ab</h3>
<p>text one ab</p>
<p></p>
</li>
<li>
<h3>ac</h3>
<p>text one ac</p>
<p></p>
</li>
Hope this makes sense! 希望这有道理!
使用标准方法,您只需在变量中跟踪当前页面,然后在页面更改时滚动到新的列表项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.