php - MySQL - 插入时重复父列值

标签 php mysql database

假设我有三个表:

类别

| column | data_type   |
|--------|-------------|
| id     | int(10)     |
| code   | int(5)      |
| name   | varchar(50) |

存款

| column | data_type   |
|--------|-------------|
| id     | int(10)     |
| code   | int(5)      |
| name   | varchar(50) |

项目

| column        | data_type   |
|---------------|-------------|
| id            | int(10)     |
| category_id   | int(10)     |
| deposit_id    | int(10)     |
| category_code | int(5)      |
| deposit_code  | int(5)      |
| name          | varchar(50) |

{parent}_id 列是外键约束。 {parent}_code 是应该在父表记录中匹配的常规列。

因此,出于某些原因,我必须在 items 表中插入相同的 code(引用父级 id)。实际上,在运行 insert 语句之前,我在执行时间(PHP 应用程序)上运行了一堆 select 语句。像这样的东西:

// Begin transaction...
$categoryCode = Category::selectCode($categoryId);
$depositCode = Deposit::selectCode($depositId);

try {
  $item = Item::insert([
    'category_id' => $categoryId,
    'deposit_id' => $depositId,
    'category_code' => $categoryCode,
    'deposit_code' => $depositCode,
    'name' => $name,
  ]);
} catch (Exception $e) {
  // Rolling back...
}
// Commiting...

这会减慢处理速度,并且不能确保基于 code 列的完整性。

我是 SQL 的新手,但我认为更好的方法是在 insert 语句中自动填充这些列。如何在 items 子表上复制 {parent}_code 列?

最佳答案

基本上,您不需要在 items 表中使用 {parent}_code。但有时,它是需要的。 如果你真的需要那些,你可以做“插入选择”而不是“插入值()” 查询看起来像这样

INSERT INTO items (category_id, deposit_id, category_code, deposit_code, name)
SELECT c.category_id, d.deposit_id, c.category_code, d.category_code, {name_val}
FROM categories as c JOIN deposits as d 
  ON (c.category_id= {c_id} and d.deposit_id= {d_id})

这是简单的交叉连接 whti 特定的 id 值。 IO 成本可能与单独的多个查询相同。但这会减少执行次数。它将减少总执行时间。

关于php - MySQL - 插入时重复父列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55047140/

相关文章:

php - 分页总是缺少1行

php - 即使使用日期对象,日期时间比较也无法在 PHP 中按预期工作

php - CodeIgniter 从 mysql 切换驱动程序 --> mysqli

php - 在 Codeigniter 中显示嵌套列表

php - 如何将图像添加到php mysql数据库?

c# - 如何有效地将 100s 到 1000s 的操作记录到数据库

php - PDO 中的表单更新数据

mysql - 使用 INNER JOIN 的 UPDATE 未更新

php - 如何在MySQL和PHP中显示所有产品的所有类别?

mysql - SQL 查询问题