简体   繁体   中英

Updating Statement in SQL/PSQL

i am new in the SQL field and i have a dumb question. Lets pretend I have a table in my database, which contains the following information:

ID        name     food
1         Max      apple
2         Anne     banana
3         Tom      kiwi

lets pretend that this is a kindergarden group that ate these foods. 2 Hors later Max ate strawberries and i want ot add this in the list as well. I want the list to look like this:

ID        name     food
1         Max      apple, strawberries
2         Anne     banana
3         Tom      kiwi

I already tried it with the UPDATE statement in SQL, but all of them want an if statement, which i personally dont understand. Does someone has an idea, how i can do it in one statement? Thanks!

The best thing you could do is to use several tables:

  • Users (ID, name)
  • Food (ID, name)
  • UserFoods (ID (optional), user_id, food_id)

Then, you could associate as many food as you want to each user. You could also add a datetime column to UserFoods if needed, etc.

*You would not use UPDATE but SET and DELETE statements...


Said that, the answer to your question would be this:

UPDATE users 
   SET food = CONCAT(food, ', ', 'strawberries') 
 WHERE name = 'Max';

Explanation: It selects the table users and it concatenates the current food , a comma and space , and strawberries to the food field of the user called Max .

I've used the user name but you should use the ID since there could be a lot of users called Max ...

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