如何根据某些偏好获取MySQL中的备用行?

时间:2013-06-30 14:52:22

标签: php mysql

我有下表 -

S.No. (Auto Increment, Primary Key)
Timestamp (Records date in yyyy-mm-dd format)
type (Records the type of document Ex. 1,2,3,etc.)
Number (Records the serial number of a particular type of document)

现在我想生成一个表,我希望按时间戳排序数据。根据{{​​1}},我想在报告的左侧和部分右侧显示一些列。所以,我想命令我的结果集首先按时间戳排序,然后按类型排序。假设我想要左侧1,2,3和右侧4,5,6。所以在我的结果集中我想要的是必须有左右两侧的交替行。防爆。

type

我试图这样做,但没有得到理想的结果。这是我想要的最终结果 -

时间戳类型时间戳类型
2012-01-01 1 2012-01-01 4
2012-01-01 1 2012-01-01 4
2012-01-01 1
2012-01-02 2 2012-01-02 6
2012-01-02 2 2012-01-02 6
2012-01-03 5
2012-01-03 5
2012-01-03 5

2 个答案:

答案 0 :(得分:1)

如果您只是在迭代结果集时收集PHP在两个变量($leftHtml$rightHtml)中生成的所有HTML代码,则无需进行排序。

完成后,您将一次性回显整个html到正确的位置。那么,行如何排序无关紧要(例如,只要您不希望它们按时间排序)。

注意:“时间戳”以及“类型”作为列名将导致长期错误,因为这些是保留字。

伪代码:

$left = "";
$right = "";
foreach ( $result as $row )
{
  if ( $row['type'] == '1' )
       $left .= "<p>left: " . $row['timestamp'];

  if ( $row['type'] == '2' )
       $right.= "<p>right: " . $row['timestamp'];
}

echo "<table><tr><td>" . $left . "</td><td>" . $right. "</td></tr></table>";

答案 1 :(得分:0)

如果您愿意,可以像这样进行查询。它正在做的是说如果类型是1,2或3,那么Side = 1(左)否则Side = 2(右)。

SELECT 
    `S.No.`, `Timestamp`, `Type`, `Number`, 
    IF(`Type` IN (1,2,3), 1, 2) as `Side`
FROM `Table`
ORDER BY `Side`, `Timestamp`, `Type`

由于我们已按Side订购,我们可以这样做:

<?php
$leftSide = true;
echo '<div class="left-side">';
while ($row = mysqli_fetch_assoc($result)) {
    if ($leftSide && $row['Side'] == 2) {
        // We've hit our first right side row so close the left side div and 
        // start theright side div
        echo '</div><div class="right-side">';
        $leftSide = false;
    }

    // Do something with the row data here
}
echo '</div>';