0

Ok, so I know there are some questions similar, but how would I update a table like this in MySQL:

+----+----------+---------+-------------------------+
| id | username | subject | content                 |
+----+----------+---------+-------------------------+
| 1  | Fred     | English | Lorem Ipsum             |
+----+----------+---------+-------------------------+

So lets say, i want to update the content in the users English book, however, I want to insert it if it is not already in there, and then in te future update it.

Antobat
  • 1
  • 3

2 Answers2

0

If one user can only have one book on a subject, you should create a unique index on (username, subject) and use this query:

INSERT
INTO    mytable (username, subject, content)
VALUES  (:username, :subject, :content)
ON DUPLICATE KEY
UPDATE  content = VALUES(content)
Quassnoi
  • 381,935
  • 83
  • 584
  • 593
0

First of all you have to create an unique index on the columns you want to be unique. Then the query is like that:

INSERT INTO `tableName` (`username`, `subject`, `content`)
VALUES ('[value 1]', '[value 2]', '[value 3]')
ON DUPLICATE KEY UPDATE `username` = '[value 1]', `subject` = '[value 2]', `content` = '[value 3]';
Andreas
  • 2,565
  • 20
  • 30