如何编写此mySQL查询以显示每列的许多数据?

时间:2015-05-06 09:27:08

标签: php mysql

我的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。

4 个答案:

答案 0 :(得分:2)

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输出

  

{ “散列”: “123456789”, “页”:[{ “页”: “mypage3”, “last_access_time”:“2015年5月6日   9时34分02秒 “},{” 页 “:” mypage2" , “last_access_time”:“2015年5月6日   9时34分02秒 “},{” 页 “:” mypage1" , “last_access_time”:“2015年5月6日   9时34分02" 秒}]}

     

{ “散列”: “999999”, “页”:[{ “页”: “mypage4”, “last_access_time”:“2015年5月6日   9时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 ..

答案 1 :(得分:0)

Mysql不支持这个东西,因为有表结构。 最正确的方法是创建PHP函数来转换数组。例如:

function convertArray($result) {
    $comparator = '';
    foreach($result as $row) {
        if ($comparator != $row['hash']) {
             $comparator = $row['hash'];
             $array[$comparator][] = $row;
        } else {
          $array[$comparator][] = $row;
        }
    } }

答案 2 :(得分:0)

SELECT IF(@tempHash = `hash`, '', @tempHash := `hash`) `hash`, page, `timestamp` 
FROM myTable
JOIN (SELECT @tempHash := '')s
ORDER BY `hash`, `timestamp`

满足你的条件吗?

编辑:按字段更改顺序 添加了哈希

答案 3 :(得分:0)

嗨,你可以试试这个......

对于像==&gt;这样的表结构hash_page(ID,散列页,时间戳)

<?php    
//this sql query groups all rows with same 'hash' value
$sql = "SELECT hash_page.id,hash_page.hash,GROUP_CONCAT(hash_page.page) as hash_pages,GROUP_CONCAT(hash_page.timestamp) as timestamps FROM hash_page GROUP BY hash";

$result = mysql_query($sql);


while($row = mysql_fetch_assoc($result)){

//this will explode comma seperated values to array
$hash_pages_arr = explode(',',$row['hash_pages']);
$timestamps_arr = explode(',',$row['timestamps']);
$count_arr = count($hash_pages_arr);

$page_timestamp_arr = array();
for($i=0; $i<$count_arr; $i++){

    $page_timestamp_arr[] = array('page'=>$hash_pages_arr[$i],'timestamp'=>$timestamps_arr[$i]);
}

$new_result[$row['hash']] = $page_timestamp_arr;
}


echo '<pre>';print_r($new_result);
?>