简体   繁体   中英

Set default value from a query result

I have are two tables:

  1. menu
      id     |     tag  
---------------------------    
      1      |      a
      2      |      a
      3      |      b
      4      |      b
  1. free_menu
      id     |   menu_id  
---------------------------    
      1      |      3
      2      |      2
      3      |      1

I want to make a category column to free_menu table which has same value in menu table, so it can be like below.

      id     |   menu_id   |     tag
------------------------------------------  
      1      |      3      |      b
      2      |      2      |      a
      3      |      1      |      a

I just want to set a default value for a new column when adding it to the table free_menu , but the following is not working:

ALTER TABLE free_menu
ADD category VARCHAR(10) NOT NULL
DEFAULT (SELECT category FROM menu WHERE id = menu_id)

Thank you for helping.

You have to split your modifications into three steps:

ALTER TABLE free_menu ADD category VARCHAR(10) NULL;
UPDATE free_menu f SET category = m.category FROM menu m WHERE m.id = f.menu_id;
ALTER TABLE free_menu ALTER category SET NOT NULL;

You may enclose these transformations into one transaction to get an atomic modification of your schema.

You cannot use a subquery while specifying default value. So I think you should user trigger for auto updating value in category column when new record is added

 Create or replace function update_cat()
returns trigger 
as $$ begin
if new.category is null then
  new.category = (select tag from menu where id = new.menu_id);
end if;
return new;
end; 
$$ language plpgsql; 

 CREATE TRIGGER
   update_category
 BEFORE INSERT ON
   free_menu
 FOR EACH ROW EXECUTE PROCEDURE
   update_cat();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM