如何在一个具有相同id的列中选择不同的值,然后在phpsqlserver中删除它们

pbossiut  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(246)

我是编程界的新手。这句话我需要帮助。我要做的是从cardindex列中选择0.1,2值,然后删除它们。只要满足条件,就必须删除行。或者最好的方法是什么。
cardindex列必须有3个值yes或yes才能执行删除。否则不执行

$query = "SELECT * FROM CardData where UserIndex='$id' and CardIndex in (0,1,2) ";
$resultados = sqlsrv_query($conn,$query);

if($query1 = sqlsrv_fetch_array($resultados)){
        if($query1 == true){
        $cro =  "DELETE FROM CardData WHERE UserIndex='$id' and CardIndex in (0,1,2)";
        $query3 = sqlsrv_query($conn,$cro); 
        }

    echo 'funciona';
    }

    else{
     echo 'no funciona';    

}
?>
a8jjtwal

a8jjtwal1#

你想要什么 or ,不是 and -否则,您将搜索 CardIndex 同时具有所有三个值,显然,这永远不会发生:

DELETE FROM CardData 
WHERE 
    UserIndex = @UserIndex
    AND (CardIndex = 1 OR CardIndex = 2 OR CardIndex = 3)

这可以缩短为 IN :

DELETE FROM CardData 
WHERE UserIndex = @UserIndex AND CardIndex IN (1, 2, 3)

请注意,这是没有意义的 SELECT 在删除值之前先对其进行预处理。你可以把枪开了 DELETE 直接:如果没有与条件匹配的行,则不会实际删除。
最后:不要连接查询字符串中的变量;这是低效的,并且将代码暴露给sql注入。相反,您应该使用参数化查询(有大量的在线资源解释了如何正确地进行查询)。
编辑
只有在所有三个记录 cardIndex 值可用于给定的 userIndex . 假设没有重复 (userIndex, cardIndex) ,一种方法是可更新的cte:

with cte as (
    select count(*) over() cnt
    from cardData
    where userIndex = @UserIndex and cardIndex in (1, 2, 3)
)
delete from cte where cnt = 3

相关问题