如何 select 具有相同 ID 的列中的不同值,然后删除它们 PHP SQL 服务器

How to select different values in a column with the same ID and then delete them PHP SQL Server

我是编程界的新手。这句话我需要帮助。我想要做的是 select 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';    

}
?>

您需要 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 注入。相反,您应该使用参数化查询(有大量在线资源可以解释如何做到这一点)。


编辑

仅当给定 userIndex 的所有三个 cardIndex 值都可用时,您才想删除所有三个记录。假设没有重复的 (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