I'm building a web application where users can answer questions. I'm trying to run a query where these answers are inserted in a table but where a user can only reply once the same question. In my case the query must check on duplicates at question_id & reply_user. (reply_id is already defined as the primary key).
For example when I have in my table answers : question_id = 1 & reply_user = John, John cannot reply anymore on question_id 1. But another user can of course.
I'm currently running this:
INSERT INTO replies (question_id, reply_user, reply_content, reply_anwer)
VALUES (:questionid, :replyuser, :replycontent, :replyanswer)
SELECT question_id, reply_user FROM replies WHERE NOT EXISTS (
SELECT question_id FROM replies
WHERE question_id = question_id AND reply_user = reply_user
)
I tried out with WHERE NOT EXISTS but I couldn't find a solution with that.
Thank's for your help
You need to unique 2 filed:
ALTER TABLE `replies` ADD UNIQUE (`question_id`,`reply_user`);
And then use this query:
INSERT INTO replies (question_id, reply_user, reply_content, reply_anwer)
VALUES (:questionid, :replyuser, :replycontent, :replyanswer)
IF question_id , reply_user exist query not run else run.
create a index unique on the two keys
ALTER TABLE replies ADD UNIQUE `preventDoubleAnswer` (`question_id`, `reply_user`) COMMENT '';
and insert the data as:
INSERT IGNORE ...
The INSERT IGNORE will insert a new data only if the unique key is satisfied.
NB: is the IGNORE param is omitted, it will throw a MYSQL error
Related
I took a look at many questions similar to mine, but I didn't get what I'm looking for, maybe you guys can help me
I have this table:
What I want to do is:
Insert a new record (regardless whether "user_id" or "course_id" are already exist or not).
BUT!, if there is a record with the same "user_id" and "course_id" and "tutorial_id", then just update "tutorial_id" and "tutorial2_id" and leave the rest as they are.
I don't want to declare column "tutorial_id" as UNIQUE, because more than a user can have the same "tutorial_id" (as you can see in the above picture).
In addition, ON DUPLICATE KEY UPDATE didn't work for me.
I'm thinking of using QUERY two times, one to select and check if record exist, and the other one whether to UPDATE or INSERT, but is that correct?
Use INSERT ... ON DUPLICATE KEY UPDATE ... syntax. For it to work.
If your user_id and course_id combination is unique you could delete the id field from your table and make those two fields a primary key.
In any other case that the id field is also needed and makes a unique combination of the three for each record then make those three fields the primary key for you table (id,user_id and course_id).
How about issuing the UPDATE first, and if no records are affected (using row_count() then INSERT? This way you only test the existence condition once.
rextester demo
update test set tutorial2_id = #tutorial2
where user_id = #user_id and course_id = #course_id and tutorial_id = #tutorial_id;
insert into test (user_id, course_id, tutorial_id, tutorial2_id)
select #user_id, #course_id, #tutorial_id, #tutorial2_id)
where row_count() = 0;
UPDATE AggregatedData SET datenum="734152.979166667",
Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667";
It works if the datenum exists, but I want to insert this data as a new row if the datenum does not exist.
UPDATE
the datenum is unique but that's not the primary key
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
Try using this:
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...
The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...
This is not too bad, but we could actually combine everything into one query. I found different solutions on the internet. The simplest, but MySQL only solution is this:
INSERT INTO wp_postmeta (post_id, meta_key)
SELECT
?id,
‘page_title’
FROM
DUAL
WHERE
NOT EXISTS (
SELECT
meta_id
FROM
wp_postmeta
WHERE
post_id = ?id
AND meta_key = ‘page_title’
);
UPDATE
wp_postmeta
SET
meta_value = ?page_title
WHERE
post_id = ?id
AND meta_key = ‘page_title’;
Link to documentation.
I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:
replace into last_recogs (id, hasher_id, hash_id, last_recog)
select l.* from
(select id, hasher_id, hash_id, [new_value] from last_recogs
where hasher_id in (select id from hashers where name=[hasher_name])
and hash_id in (select id from hashes where name=[hash_name])
union
select 0, m.id, h.id, [new_value]
from hashers m cross join hashes h
where m.name=[hasher_name]
and h.name=[hash_name]) l
limit 1;
This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.
This is actually a form to update the team members who work for a specific client, When i deselect a member then it's status turns to 0.
I have a table with all unique records. table consists of four columns -
first column is `id` which is unique and auto_incremented.
second column is `client_id`.
third column is `member_id`. (these second and third columns together make the primary key.)
fourth column is `current` which shows the status (default is 1.).
Now i have a form which sends the values of client_id and member_id. But this forms also contains the values that are already in the table BUT NOT ALL.
I need a query which
(i) `INSERT` the values that are not already in the table,
(ii) `UPDATE` the `current` column to value `0` which are in the table but not in the form values.
here is a screenshot of my form.
If (select count(*) from yourtable where client_id = and member_id = ) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
First of all check if the value exists in the table or not, by using a SELECT query.
Then check if the result haven't save value so it will be inserted, else show an error .
This would be a great time to create a database stored procedure that flows something like...
select user
if exists update row
else insert new row
stored procedures don't improve transaction times, but they are a great addition to any piece of software.
If this doesn't solve your problem then a database trigger might help out.
Doing a little research on this matter might open up some great ideas!
Add below logic in your SP
If (select count(*) from yourtable where client_id = <value> and member_id = <value>) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
if you want simple solution then follow this:
*) use select with each entry in selected team.
if select returns a row
then use update sql
else
use insert sql.
In your case member_id & client_id together makes the primary key.
So , you can use sql ON DUPLICATE KEY UPDATE Syntax.
Example:
$sql="INSERT INTO table_name SET
client_id='".$clientId."',
member_id='".$member_id."',
current='".$current."'
ON DUPLICATE KEY
UPDATE
current = '".$current."'
";
In this case when member_id & client_id combination repeats , it will automatically executes update query for that particular row.
This question already has answers here:
MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?
(3 answers)
Closed 10 months ago.
I have a table rating with these fields rate_id, game_id, rating, ip. Let suppose that these fields has the following values 1,130,5,155.77.66.55
When a user try to vote for a game, I want with mysql to check if he has already vote for this game so mysql will check if ip and game_id already exists, if they exists then mysql will update the value of rating otherwise will create a new entry.
What is a efficient way to do this?
Create unique index that covers ip + game_id. After that you can use INSERT ... ON DUPLICATE KEY UPDATE statement.
So the total query will be something like
INSERT INTO rating (rate_id, game_id, rating, ip) VALUES (1,130,5,'155.77.66.55')
ON DUPLICATE KEY UPDATE rating = 5
MySQL allows an on duplicate key update syntax for INSERT. So if you set your key to be game_id, user_id (or whichever way you identify the user) then you can use INSERT...on DUPLICATE KEY UPDATE which will do just that:
http://dev.mysql.com/doc/refman/5.5/en/insert.html
You could also take a look at REPLACE INTO. Maybe not for this project but for future reference:
REPLACE works exactly like INSERT,
except that if an old row in the table
has the same value as a new row for a
PRIMARY KEY or a UNIQUE index, the old
row is deleted before the new row is
inserted
from: dev.mysql.com
// check to see if exist
$sql = "SELECT ip FROM rating WHERE ip=$ip && game_id={$game_id}";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(isset($row['ip'])){
mysql_query("UPDATE HERE");
}else{
mysql_query("INSERT HERE");
}
What I am trying to achieve: a quiz system with user account and cumulative results table.
Process:
-User sets up an account
-User logs in
-User completes quiz
-Answers go into results table
-Results table displayed
My database structure:
Table 1: users
user_id
username
password
email
Table 2: quizzes
quiz_id
title
Table 3: questions
question_id
quiz_id
question
question_notes
Table 4: answers
answer_id
question_id
user_id
answer
answer_notes
Table 5: responses
response_id
quiz_id
user_id
submit_time
The questions will be output from Table 3 via a SELECT.
What I am looking for some pointers for is how I can ensure the relationships for each quiz entry is consistent, so when I run the INSERT statements the IDs are consistent (so the "question_id" for Table 3 and Table 4 are the same, for example)
I am thinking I will have 2 INSERT statements for Table 4 and Table 5. In these insert statements, is there a way to ensure the relationships match?
I am having some trouble visualising how this will work for entering the data into the database, once I've got this figured out I can tackle using the data.
Any pointers to decent tuts or a bit of insight into possible form processing would be much appreciated.
Many Thanks
There's LAST_INSERT_ID() function in MySQL ( mysql_insert_id() in PHP ) that will return auto_increment id from last insert query. This will let you keep consistency.
See here for more details:
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Foreign keys and transactions enforce referential integrity...
For example:
Answers
question_id is a foreign key to question.id
user_id is a foreign key to user.id
(These are set in the table definition)
You insert in to answers like so (sloppy pseudocode):
begin transaction
int qid = select id from question
int uid = select id from user
insert (qid,uid,...) into answers
commit transaction