[英]MySQL: multi rows result VS single row result
I have these three tables, 我有这三个桌子,
page
table page
表
page_id page_title
1 a
content
table content
表
content_id content_text
1 text one
2 text two
content structure
table content structure
表
page_id content_id order_in_page
1 1 1
1 2 2
my working sql, 我的工作SQL,
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.page_url = 'a'
result, 结果,
page_id page_title content_text order_in_page
1 a text one 1
1 a text two 2
the result I am after 我追求的结果
page_id page_title content_1 content_2 content_3 content_4
1 a text one text two null null
How can I make the multi-row result into a single row result? 如何将多行结果变成单行结果?
Or maybe the multi rows result is better and faster than a single row result that I want? 还是多行结果比我想要的单行结果更好,更快?
EDIT: 编辑:
the reason I want a single row result is that I can just call the content_# by doing this, 我想要单行结果的原因是我可以通过执行此操作来调用content_#,
echo $page['content_1'];
just like I call the title, 就像我称呼标题一样
echo $page['page_title'];
Again, your thinking is in the wrong spot, 同样,您的想法是错误的, this, if it is possible to do, would be discouraged, inefficient and probably is not possible. 如果可能的话,这将被劝阻,效率低下并且可能是不可能的。
Instead, handle the data in the loop and do with it what you want there, 而是处理循环中的数据,并在其中处理您想要的数据, it may seem like it is more inefficient in the loop, but I assure it is not. 似乎在循环中效率更低,但我保证不是。
foreach ($dataFromSQL as $data) {
$page[] = $data;
}
// Later on when you want to access it:
echo $page[0]['page_title'];
echo $page[0]['content_text'];
Where 0 would be the first row, 1 would be the second etc. 其中0是第一行,1是第二行,依此类推。
You can do this quite easily using GROUP BY
with an IF
statement for each column you want to transpose. 您可以对要转置的每一列使用带有IF
语句的GROUP BY
来轻松完成此操作。 When MAX evaluates it will always evaluate a non-null value as greater than NULL. MAX求值时,它将始终将大于NULL的非null值求为。
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.page_url = 'a'
GROUP BY page_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.