【问题标题】:How to select different values in a column with the same ID and then delete them PHP SQL Server如何在具有相同 ID 的列中选择不同的值然后删除它们 PHP SQL Server
【发布时间】:2020-06-01 23:00:58
【问题描述】:

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

}
?>

【问题讨论】:

    标签: php sql sql-server where-clause sql-delete


    【解决方案1】:

    您需要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)
    

    请注意,在删除它们之前SELECTing 值是没有意义的。您可以直接触发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
    

    【讨论】:

    • in (1,2,3) 确实有效,但不满足条件,即 CardIndex 包含强制值 0,1,2。如果这 3 个值不存在,则不应执行删除。 CardIndex 列必须具有 3 个值 yes 或 yes 才能执行删除。否则不会执行。
    • @IchigoKurosaki:啊,好的。那就更有意义了。请参阅我的更新答案。
    • 运行时在 php 中不起作用 :( 警告:sqlsrv_fetch_array () 期望参数 1 是资源,$ query = "with cte as (SELECT count (*) over () cnt FROM CardData where UserIndex = $id and CardIndex in (1, 2, 3))";
    • @IchigoKurosaki:您似乎忘记了查询的一部分(以delete 开头的那个)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2017-04-23
    • 1970-01-01
    • 2013-12-01
    • 2021-03-18
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多