当前位置: 代码迷 >> Sql Server >> 请问一个SQL语句替换有关问题,
  详细解决方案

请问一个SQL语句替换有关问题,

热度:102   发布时间:2016-04-27 12:22:39.0
请教一个SQL语句替换问题,在线等!!!!!
做一个分页的。
想把形如:

SELECT u.id,u.name FROM user as u ORDER BY u.id DESC LIMIT 0 10
SELECT u.id,u.name FROM user as u WHERE u.id=12 ORDER BY u.id DESC

替换成

SELECT COUNT(*) FROM user as u ORDER BY u.id DESC LIMIT 1
SELECT COUNT(*) FROM user as u WHERE u.id=12 ORDER BY u.id DESC LIMIT 1


也就是形式如

SELECT xxxxx FROM ***** WHERE ***** ORDER BY **** LIMIT XXXXX
SELECT xxxxx FROM ***** WHERE ***** ORDER BY **** 

其中 XXXXX 部分进行替换。



PHP 怎么写正则。。。

------解决方案--------------------
PHP code
$str="SELECT u.id,u.name FROM user as u WHERE u.id=12 ORDER BY u.id DESC limit 10";echo preg_replace("/^(select ).+? (from .+?)(limit (\d{1,}(\,\d{1,})?))?$/i","\\1 count(*) \\2 limit 1;",$str);
------解决方案--------------------
<?php

$str="SELECT u.id,u.name FROM user as u WHERE u.id=12 ORDER BY u.id DESC limit 1,10";
echo preg_replace("/^(select ).+ (from.+?)( limit [0-9\,]+){0,1}$/i","\\1 count(*) \\2 limit 1",$str);
echo "<br />";
$str="SELECT u.id,u.name FROM user as u WHERE u.id=12 ORDER BY u.id DESC";
echo preg_replace("/^(select ).+ (from.+?)( limit [0-9\,]+){0,1}$/i","\\1 count(*) \\2 limit 1",$str);
?>
  相关解决方案