INSERT INTO SELECT MAX From Another Table



我有一个INSERT INTO SELECT语句,它现在有一个静态数字。我想通过使这个数字成为另一个表中字段的MAX来使它成为动态的。

声明是:

INSERT INTO checklist_items (checklists_id, checklist_item_types_id, is_completed)
SELECT 3, cit.id, false
FROM checklist_item_types cit
WHERE cit.is_active = 't'

以下是每个表格的示例:

这是我的checklists表格:

id  checklist_date  notes
1   "2018-07-23"    "Fixed extra stuff"
2   "2018-07-24"    "These are some extra notes"
3   "2018-07-25"    "Notes notes"

这是我的checklist_items表,数据减少:

id  checklists_id  checklists_item_types_id  is_completed
1   1              1                         false
2   1              2                         true
3   1              3                         true
...
34  2              16                        true
35  2              17                        true
36  2              18                        true

这里是checklist_item_types,数据减少:

id  description                        is_active
1   "Unlock Entrances"                 true
2   "Ladies Locker Room Lights"        true
3   "Check Hot Tubs (AM)"              true
...
15  "Water Softener Boiler Room"       false
16  "Water Softener Laundry"           true
17  "Check/Stock Fire Logs"            true
18  "Drain Steam Lines (4 locations)"  true

如何将SELECT 3更改为类似SELECT MAX(checklists.id)的内容?

只需将3替换为subquery:

INSERT INTO checklist_items (checklists_id, checklist_item_types_id, is_completed)
SELECT (SELECT MAX(id) FROM checklists), cit.id, false
FROM checklist_item_types cit
WHERE cit.is_active = 't'

YOu可以通过使用内部联接和组

INSERT INTO checklist_items (checklists_id, checklist_item_types_id, is_completed)
SELECT max(c.id), cit.id, false as status
FROM checklist_item_types cit
INNER JOIN checklists c  ON c.id =  cid.checklists_id
WHERE cit.is_active = 't'
group by  cit.id, status 

最新更新