PostgreSQL将表B中每条记录的一条记录插入表A中

时间:2018-07-26 00:11:13

标签: sql postgresql

我有三个表checklistschecklist_itemschecklist_item_types。我想在我的预定工作中为INSERT中符合条件(checklist_items列为checklist_item_types)中的每个记录,is_active中的记录true。 / p>

这是我的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,数据减少了(例如,假设除15外,所有is_active都是true

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

因此,当我的工作运行时,我希望checklist_items得到17条新记录(18 checklist_item_types减去1,因为它是false的{​​{1}})。 / p>

作业运行一次后,“新” is_active如下所示:

checklist_items

2 个答案:

答案 0 :(得分:1)

您似乎想要insert . . . select

insert into checklist_items (checklists_id, checklists_item_types_id, is_completed)
    select 3, cit.checklists_item_types_id, false
    from checklist_item_types cit;

答案 1 :(得分:0)

我建议创建类以与数据库进行通信。这是提取所需的checklist_item_types的类的一部分。如您所见,您需要在database.php文件中使用另一个类“ DatabaseConn”来打开与数据库的连接。您将需要一些PHP代码来调用此函数,并且还需要将该函数添加到checklist_items表中。

<?php
require_once("model/database.php");
class checklist_item_types extends DatabaseConn
{
...
    public function get_records_by_id_and_completed($starting_id, $is_completed) {
        global $dbConn;
        $sql = "SELECT * FROM checklist_item_types 
           WHERE id >= $starting_id AND is_completed = $is_completed";
        try {
            $statement = $dbConn->prepare($sql);
            $statement->execute();
            $result = $statement->fetchAll();
            $statement->closeCursor();
            return $result;
        } catch (PDOException $e) {
            echo $sql . "<br>" . $e->getMessage();
        }
    }
...
}
?>
相关问题