如果数据库中存在连续数据,如何绕过?

时间:2015-08-10 08:32:53

标签: php mysql

我的表包含id和group。

id        group
 1        alpha
 2        beta
 3        omega

我的验证码是:

$validate_query = "SELECT * FROM table_test WHERE id = '{$id}' ";
                $rs = mysql_query($validate_query,$connection);
                if(mysql_num_rows($rs) != 0) {
                    echo "<span class='confirmation'>Oops! Data exist. Try another one.</span>";
                } 
                else { 

                    $query = "UPDATE table_test SET 
                            group= '{$group}'               
                            WHERE id = '{$id}'                      
                            ";
                    $result = mysql_query($query, $connection);  

但我的目标就是这样......

**example:**
if the user want to edit the field group value(ex. alpha) into (beta).. 
then the value of id 1 and 2 is beta... 

现在我只想检查值是否存在..我只是想取回原始值(alpha)以便没有重复....

3 个答案:

答案 0 :(得分:2)

你只需将查询更改为此 -

$validate_query = "SELECT * FROM table_test WHERE group = '{$group}' ";

答案 1 :(得分:0)

将查询字符串更改为:

$validate_query = "SELECT * FROM table_test WHERE group = '{$group}' AND id != '{$id}'";

如果你想在每种情况下都进行数据库操作。比:

                $validate_query = "SELECT * FROM table_test WHERE group = '{$group}' AND id != '{$id}'";
                $rs = mysql_query($validate_query,$connection);
                if(mysql_num_rows($rs) != 0) {
                    $query = "UPDATE table_test SET 
                            group= group               
                            WHERE id = '{$id}'";


                } 
                else { 

                    $query = "UPDATE table_test SET 
                            group= '{$group}'               
                            WHERE id = '{$id}'";
                 }
                 $result = mysql_query($query, $connection);  

答案 2 :(得分:0)

您可以在列GROUP上使用unique constraint 因此,当您尝试使用重复值进行更新时,更新将触发错误。

其他解决方案是在更新语句中添加exist子句。

即:

UPDATE table_test 
   SET group= '{$group}'               
 WHERE id = '{$id}'
   AND NOT EXISTS ( select 1 
                      FROM table_test 
                     WHERE group= '{$group}'  )

现在语句不会触发错误,您可能需要检查更新了多少行才能确定该组是否已存在。