【问题标题】:Respecting unique_constraint without updating primary key尊重 unique_constraint 而不更新主键
【发布时间】:2020-06-20 00:43:24
【问题描述】:

我在 mysql 中有一个表,假设: ID - year - month

我在 yearmonth 上放置了一个 unique_constraint。这样一年就不可能有两个相同的月份。

ID 用于检索年份和月份的组合。假设我们有以下值:

ID -  year  -  month
1  -  20    -  1
2  -  20    -  2
3  -  20    -  5

那么ID 3 将是 2020 年 5 月。但是,此表是动态构建的。我上传了具体的数据,需要插入所有年月的组合。

首先我使用 MySQL 突击队 REPLACE INTO,因为我认为它不会添加非唯一行。而且它不会添加非唯一行,但每次都会更新ID,导致我的外键搞砸了。

我该如何解决这个问题?只使用INSERT?由于 unique_constraint,插入将失败并返回错误。

现在我已经这样修复它了:

$conn = new mysqli(HOST, USER, PASS, DTBS);
         $stmt = $conn->prepare("SELECT ID FROM periods WHERE month=? AND year=?");
         $stmt->bind_param("ii", $month_, $year_);
         $month_ = $month;
         $year_ = $year;
         $stmt->execute();
         $stmt->bind_result($id);
         $stmt->fetch();
         $rows = $stmt->num_rows;
         $stmt->close();


         if ($rows == 0) {
             $stmt = $conn->prepare("INSERT INTO periods (year, month) VALUES (?, ?)");
             $stmt->bind_param("ii", $year_, $month_);
             $year_ = $year;
             $month_ = $month;
             $stmt->execute();
             $stmt->close();
         }
          $conn->close();

【问题讨论】:

  • $stmt->num_rows 在这里不起作用。先获取结果
  • @Dharman 我正在提取,$stmt->fetch()?
  • 我的意思是你需要打电话给get_result()store_result()
  • @Dharman 哦,是的,你是对的!谢谢。
  • 如果您只是从 PHP 开始,那么我建议您学习 PDO 而不是 mysqli。这更容易

标签: php mysql sql sql-update sql-insert


【解决方案1】:

你可以使用INSERT ... ON DUPLICATE KEY:

insert into periods(year, month)
values (?, ?)
on duplicate key update year = values(year)

这利用了(year, month) 的唯一约束。当遇到重复的元组时,MySQL 不会insert 它,而是转到on duplicate key 子句,在该子句中执行虚拟更新。

【讨论】:

  • 像魅力一样工作!我已经对这个问题进行了很多研究,但只是偶然发现了REPLACE INTO 或带有 if 语句等的非常复杂的 SQL 语法。最好和最简单的解决方案!很快就会接受。
猜你喜欢
  • 2017-10-24
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 2014-06-17
  • 2020-11-05
  • 1970-01-01
  • 2016-03-06
相关资源
最近更新 更多