【发布时间】:2016-12-13 15:42:42
【问题描述】:
我知道 varchar 类型的列是不可递增的,但我想做这样的事情:
当插入重复值时,新的值将在末尾用数字标记。
例如,我们在数据库中的列上有 post-name。输入了另一个值 post-name,因此下一个将是 post-name-2,然后是 post-name-3。
我用php编写了一些东西,但不是很方便。
$post_url_ = $post_url." %";
$stmt_check1 = $this->conn->prepare("SELECT * FROM post WHERE post_url LIKE :post_url ");
$stmt_check2 = $this->conn->prepare("SELECT * FROM post WHERE post_url = :post_url ");
$stmt_check1->bindparam(":post_url",$post_url_);
$stmt_check2->bindparam(":post_url",$post_url);
$stmt_check1->execute();
$stmt_check2->execute();
$rows1 = $stmt_check1->rowCount();
$rows2 = $stmt_check2->rowCount();
if($rows1<=0 && $rows2==1) {
$repeat_no = $rows1+1;
$post_url = $post_url."-$repeat_no";
}
if($rows1>0){
$repeat_no = $rows1+1;
$post_url = $post_url."-$repeat_no";
}
【问题讨论】:
-
在 db 级别我认为最好为此创建一个单独的字段。否则,您无法将
post-1与post-2进行比较,如果您需要为UI 做一些连接,请在SELECT上进行 -
@JuanCarlosOropeza 所以我无法在数据库级别进行设置?
-
@JuanCarlosOropeza 在考虑了更多之后,您建议我创建另一个字段,例如:duplicated_version。该字段将保存该特定 url 的数量,与创建后输入的次数一样多。像柜台一样,谢谢你,这解决了它最好的。
-
@JuanCarlosOropeza 请添加您的建议作为答案,以便我接受:)。
标签: php mysql auto-increment varchar