如何在Mysql查询中给出带条件记录的序列号

时间:2017-06-12 10:52:25

标签: php mysql conditional

我有一张表格,其中存储了两种类型的产品。一个表用于具有唯一ID的单个项目,另一个用于组合具有相同Id的项目,如下图所示:

Mysql Table Snip

我必须在我的SQL中运行更新查询,这将为此提供序列号Sno。 如果DealCode相同,则分配相同的序列号,否则递增它。请注意,如果DealCode为0,那么它应该递增。 0是针对不同的产品。

1 个答案:

答案 0 :(得分:0)

可能会对你有帮助 -

您可以通过为此

创建存储过程来执行上述任务

假设您有一个名为" product"

的表

存储过程定义 -

DELIMITER $$ 
DROP PROCEDURE IF EXISTS assignSerialNo$$ 
CREATE PROCEDURE `assignSerialNo`() 
BEGIN 
DECLARE x  INT; 
DECLARE y  INT; 
DECLARE data  INT; 
DECLARE countNonZeroRecord  INT; 
DECLARE countZeroRecord  INT;

SET x = 1; 
SET countNonZeroRecord = ( SELECT count(*) FROM  product where DealCode != 0 ); 
SET countZeroRecord = ( SELECT count(*) FROM  product where DealCode = 0 );


WHILE x  <= countZeroRecord  DO 
SET data = ( SELECT WebTransactionDetailNo from product WHERE Sno = 0 LIMIT 1 ); 
UPDATE product SET Sno = x WHERE  WebTransactionDetailNo = data; SET  x = x + 1;  
END WHILE;

SET y = 1; 
WHILE y  <= countNonZeroRecord  DO 
SET data = ( SELECT DealCode from product WHERE Sno = 0 AND DealCode !=0 LIMIT 1 ); 
UPDATE product SET Sno = x WHERE  DealCode = data; SET  x = x + 1;  
SET  y = y + 1; 
END WHILE;

END

调用程序以设置序列号。记录使用语法 -

调用assignSerialNo()

**

对于PHP:

如果您想使用核心php执行上述任务,那么您可以使用以下代码:
希望对你有帮助     

$connection = mysqli_connect("hostName","userName","password","databaseName");
$x=0; 

$nonZeroDealCodeResult = runQuery("SELECT count(*) as countRecords FROM  product where DealCode != 0",$connection);
$zeroDealCodeResult = runQuery("SELECT count(*) as countRecords FROM  product where DealCode = 0",$connection);

while($zeroDealCodeResult['countRecords']) { 
$x++;
$searchQuery = "SELECT WebTransactionDetailNo from product WHERE Sno = 0 AND DealCode = 0  LIMIT 1";
$data = runQuery($searchQuery,$connection);
mysqli_query($connection, "UPDATE product SET Sno = {$x} WHERE  WebTransactionDetailNo = {$data['WebTransactionDetailNo']}"); 
$zeroDealCodeResult['countRecords']--;
}

while($nonZeroDealCodeResult['countRecords']) {
$x++;  
$searchQuery = "SELECT DealCode from product WHERE Sno = 0 AND DealCode !=0 LIMIT 1";
$data = runQuery($searchQuery,$connection);
mysqli_query($connection, "UPDATE product SET Sno = {$x} WHERE  DealCode = {$data['DealCode']}"); 
$nonZeroDealCodeResult['countRecords']--;
}

function runQuery($searchQuery,$connection) {
$dataQuery = mysqli_query($connection, $searchQuery); 
$data = mysqli_fetch_assoc($dataQuery) ;
return $data;
}

?>