从另一张表中插入SELECT MAX

时间:2018-07-26 13:05:09

标签: sql postgresql

我有一个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)的内容?

2 个答案:

答案 0 :(得分:5)

只需将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'

答案 1 :(得分:1)

您可以使用内部联接和分组依据

  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