我的mySQL表如下
id - hash - page - timestamp
1 - ig35sdf89 - page1 - 2015-05-06 12:03:54
2 - ig35sdf89 - page2 - 2015-05-06 12:06:54
3 - ig35sdf89 - page1 - 2015-05-06 12:08:54
4 - xgd98rgf - page1 - 2015-05-06 12:10:54
5 - aaaat43gr - page3 - 2015-05-06 12:12:54
我的问题是要使用什么 mySQL 查询来显示类似我将通过时间戳显示每个哈希顺序路径的位置:
ig35sdf89 - page1 - 2015-05-06 12:08:54
- page2 - 2015-05-06 12:03:54
- page1 - 2015-05-06 12:06:54
xgd98rgf - page1 - 2015-05-06 12:10:54
aaaat43gr - page3 - 2015-05-06 12:12:54
我正在使用 PHP。
最佳答案
mysql 支持 group_concat
。哪个正好支持这个用例
所以如果你的表定义为
表定义
create table pages
(
id integer auto_increment primary key not null,
hash varchar(10) not null,
pagename varchar(128) not null,
last_access_time timestamp not null
);
你可以用这个
查询
select
hash, group_concat(pagename, last_access_time SEPARATOR ';\n')
from
pages
group by hash
;
或者可以返回 json 以与 php json_decode
一起使用:
查询输出json
select
concat('{', prty_hash, ',"pages":[', group_concat(json_page SEPARATOR ','), ']}') as json_prt
from
(
select
concat('"hash":"', hash, '"') as prty_hash,
concat('"page":', pagename) as prty_pagename,
concat('{', '"page":"', pagename, '",', '"last_access_time":"', last_access_time, '"}') as json_page
from
pages
) prty
group by prty_hash
;
这给出了
json输出
{"hash":"123456789","pages":[{"page":"mypage3","last_access_time":"2015-05-06 09:34:02"},{"page":"mypage2","last_access_time":"2015-05-06 09:34:02"},{"page":"mypage1","last_access_time":"2015-05-06 09:34:02"}]}
{"hash":"999999","pages":[{"page":"mypage4","last_access_time":"2015-05-06 09:34:02"}]}
链接到 sqlfiddle
这现在可以在 php 中使用,例如:
php
<?php
$servername = "localhost";
$username = ...;
$password = ...;
$dbname = ...;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// GET
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = <<<heredoc
select
concat('{', prty_hash, ',"pages":[', group_concat(json_page SEPARATOR ','), ']}') as json_prt
from
(
select
concat('"hash":"', hash, '"') as prty_hash,
concat('"page":', pagename) as prty_pagename,
concat('{', '"page":"', pagename, '",', '"last_access_time":"', last_access_time, '"}') as json_page
from
pages
) prty
group by prty_hash
;
heredoc;
$dbResult = $conn->query($sql);
$appResult = array();
while($row = $dbResult->fetch_assoc()) {
$json_res_obj = json_decode($row['json_prt']);
// do something with the object, render/echo it on the page etc..
}
$conn->close();
}
else
{
die("Invalid request");
}
?>
注意:未经测试的 php..
关于php - 如何编写此 mySQL 查询以在每一列中显示多个数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30072711/