如何从数据库中打印连续值?

时间:2015-12-04 00:00:17

标签: php mysql

这是mySQL数据库中的表data

我想做的是:

  • 如果id退出no 01,02和03,则打印连续值和no 01.如果没有,则打印最低缺失no和最低id,其中缺少值。

例1:

    +-----------+
    | id  | no  | 
    +-----------+
    | 01  | 01  | 
    | 01  | 02  | 
    | 01  | 03  | 
    | 02  | 01  | 
    | 02  | 02  | 
    | 02  | 03  | 
    | 03  | 01  | 
    +-----------+

我希望的结果:

id = 03,no = 02

例2:

    +-----------+
    | id  | no  | 
    +-----------+
    | 01  | 01  | 
    | 01  | 02  | 
    | 01  | 03  | 
    | 02  | 01  | 
    | 02  | 02  | 
    | 02  | 03  | 
    +-----------+

我希望的结果:

id = 03,no = 01

我的代码遗失了一些:

$pdo = Database::connect();             
$sql = "SELECT  `id`, `no` FROM `data`";
$q = $pdo->prepare($sql);
$q->execute();
$result = $q->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);  

foreach  ($result as $key => $value) {
    if (in_array("01", $value) AND in_array("02", $value) AND in_array("03", $value)) {
       echo "id=";
       echo "0";
       echo $key + 1;
       echo "<br>";
       echo "no=01";
       echo ",";
    } else {
       echo "id=".$key;
       echo ",";
       foreach  ($value as $row => $number) {
           echo "no=0";
           echo $number + 1;
           echo ",";
      }
    }
    echo "<br>";    
}   

我的结果示例1:

ID = 02,没有= 01

ID = 03,没有= 01

ID = 03,没有= 02

例如2:

ID = 02,没有= 01

ID = 03,没有= 01

1 个答案:

答案 0 :(得分:0)

考虑没有PHP条件循环的纯SQL解决方案。具体来说,下面使用派生表,case / when逻辑和联合查询的组合:

# RETURN EXISTING RECORDS AS IS
SELECT data.`ID`, 
       data.`No`
FROM data

UNION

# NEXT CONSECUTIVE ROW
SELECT 
      CASE WHEN NextNo = 3 THEN NextID +1 ELSE NextID END As PHPID,
      CASE WHEN NextNo = 3 THEN 1 ELSE NextNo + 1 END As PHPNo    
FROM

     (SELECT data.`ID` As NextID, 
             data.`No` As NextNo
      FROM data
      ORDER BY data.`ID` DESC, data.`No` DESC
      LIMIT 1) As dT

示例1 OUTPUT

ID  No
1   1
1   2
1   3
2   1
2   2
2   3
3   1
3   2

示例2 OUTPUT

ID  No
1   1
1   2
1   3
2   1
2   2
2   3
3   1