MySQL-插入时复制父列值

时间:2019-03-07 15:16:11

标签: 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是常规列,应在父表记录中匹配。

因此,由于某些原因,我必须在code表上插入相同的id(指代父项items)。实际上,在运行select语句之前,我正在执行时运行一堆insert语句(PHP应用程序)。像这样:

// 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语句中自动填充这些列。如何复制{parent}_code子表上的items列?

2 个答案:

答案 0 :(得分:1)

基本上,您无需在项目表中使用{parent} _code。但有时候,这是必需的。 如果您确实需要这些,可以执行“插入选择”,而不是“插入values()” 奎里看起来像这样

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})

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

答案 1 :(得分:1)

项目表中不需要category_codedeposit_code

因此您的示例代码变为

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

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

当您想查看此项的category_codedeposit_code时,只需使用category_iddeposit_id联接表

SELECT i.name as item_name, c.category_code, d.deposit_code, ....
FROM item i
    JOIN category c ON c.id = i.category_id
    JOIN deposit d ON d.id = i.deposit_id
WHERE .......
相关问题