How to use replace to non unique keys? mysql [duplicate] - mysql

This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 8 years ago.
I have this table:
rating | businessId | userId
============================
1 200 1
2.5 200 2
the user can't has two rows with the same businessId,
for example:
rating | businessId | userId
============================
1 200 1
2.5 200 1
this's incorrect;
my server receive the businessId,userId and rating.
then it should update the row which has the same userId, and businessId if exist, else create new row.
How could I implement that with one query ?

It is possible to perform a single query which will either insert or update a row, by using MySQL procedures. However, it's very likely to be better to test whether the row exists first in your chosen language, and then either insert or update as appropriate. This will allow you to give appropriate feedback to the user, and other things which depend on whether the row existed before.

Suppose you get these three values #rating ,#userId,#businessId then you would write you UPSERT (UPDATE/Insert) query something like this.....
IF EXISTS (SELECT 1 FROM dbo.TableName
WHERE userId = #userId AND businessId = #businessId)
BEGIN
UPDATE dbo.TableName
SET businessId = #businessId
,rating = #rating
WHERE userId = #userId
END
ELSE
BEGIN
INSERT INTO dbo.TableName (userId, businessId, rating)
VALUES (#userId, #businessId, #rating)
END

Related

MySQL Fill multiple unused rows with data in a table with pre-populated data

I have a table with pre-populated data that looks similar to this:
Id
giftCode
userId
1
AGiftCode
42342
2
AnotherCode
NULL
3
AnotherOne
NULL
4
Code
NULL
5
Code2
NULL
6
Code3
NULL
Multiple users are simultaneously assigned to the pre-populated data at certain times, and I am currently achieving this using the following query multiple times:
UPDATE table SET userId = "xxxxx" WHERE userId is NULL LIMIT 1
Is there a way to do the same thing, but with a single UPDATE statement to insert x number of userId's into the next x number of open rows?
Only the userIds to insert and the number of userIds to be inserted is known at the point of updating.
One approach uses SELECT ... FOR UPDATE:
SELECT giftCode FROM yourTable WHERE userId IS NULL LIMIT 1 FOR UPDATE;
UPDATE yourTable SET userId = 'xxxxx' WHERE giftCode = 'code from above';

update row if already exist or else insert new record in table using mysql

SELECT * FROM user_referral;
id user_id new_user_id bonus_type amount
1 123 own 25
2 234 own 25
3 123 456 referral 25
SELECT * FROM user_points;
id user_id referral_points
1 123 50
2 234 25
I am working for an application and I have two tables like above. If user join my application than he will get some bonus.
when user join he get 25 rupees and when he refer another friend again he get 25 more.So first record will come to user_referral table where individual amount will be stored and for particular user total amount will be stored in user_points table.
Now I am writing trigger in user_referral table to update amount in user_points table using mysql, I want to check if user already exist in user_points table that amount should be updated else it should insert new record.
I tried if else condition but its not working, I don't know how to check duplicate records..
if (SELECT user_id FROM user_points WHERE user_id IN (SELECT new.user_id FROM user_referral)) then
update user_points set
referral_points=referral_points+new.point,
updated_time=new.inserted_time;
else
INSERT INTO user_points (user_id,referral_points,updated_time)
VALUES (new.user_id, new.point, new.inserted_time);
end if;
Also I tried using on duplicate key update, but in my case it is inserting new row instead it should update previous one.
Any help will be appreciated..
Consider the insert ... on duplicate key syntax:
insert into user_points(user_id, referral_points)
values(:user_id, :referral_points)
on duplicate key update referral_points = referral_points + values(referral_points)
For this to work, you need a unique constraint on user_points(user_id).
When an insert occurs on a user_id that already exists, MySQL goes to the on duplicate key clause, where the new referral_points value is added to the existing value.

MySql - Add new row for every userId in the table

Below is the table i am trying to write a query for to add new rows for every user.
My question is how do i add a new row for every user? Which means for userId 2 I add AccId 4 and similarly for 7 and 8. Since there is no concept of for loop in sql, do i make use of while? If so, how to loop through the userIds since the IDs are not in equal increments?
something like this maybe:
Insert Into mytable (UserID, AccID)
Select UserID, max(accId)+1
From MyTable
Group By UserID
You can re-run it every time, you will create the next value.
Untested on a MySql server:
INSERT INTO MyTable ( ID, AccId )
SELECT MyValues.ID, MyValues.Espr1
FROM (SELECT MyTable.ID, Max([AccId]+1) AS Espr1
FROM MyTable
GROUP BY MyTable.ID) AS MyValues;
Basically we prefetch Id a AccId grouping the values of Id and grabbing the Max of AccId.
Then we add these rows to the main table. Repeating the query we will add the value 5 (AccId) and so on, always adding 1

MySQL - Update field in insert into query from select query

I have following two tables A and B.
I would like to insert records from table A into table B but with new orderNum value as and when new records are being added into table B.
I have following query but not working as expected.
INSERT INTO B (refId, userId, orderNum)
SELECT id, '1', (SELECT count(refId) + 1 FROM B WHERE userId = 1) as orderNum
FROM A
WHERE is_mendatory IS NOT NULL
ORDER BY is_mendatory ASC
Let say I have 3 records exist in table B and using SELECT query I am going to insert 5 more records. So those new 5 records should be inserted with orderNum from 4,5,6,7,8.
But currently it only sets 4 as orderNum for new 5 records.
Can anybody suggest something on this?
Edit:
I am getting on 4 in orderNum field for new 5 records.
Create a before insert trigger,count the rows in B for each INSERT,store the number in a variable,update the table with the number of rows.
DELIMITER //
CREATE TRIGGER orderNum_after_insert
BEFORE INSERT
ON B FOR EACH ROW
BEGIN
SET #orderNo:=(SELECT COUNT(*) FROM B);
SET NEW.orderNum=#orderNo;
END; //
DELIMITER ;

how to INSERT and DELETE records in 1 query?

Hi I want to build a (Follow/Unfollow) button,
which should FOLLOW a page by 'adding' a record in a table {table columns are UserID and PageID} if the record doesn't exist,
or UNFOLLOW a page by 'removing' the record from the table if the record already exist
I know I can handle this in the PHP code by creating 2 queries, BUT I want to know if I can do it with 1 query using 'if statment' or something else!!
Thanks in advance.
In Oracle, you can use the MERGE statement with the DELETE clause, consider:
SQL> create table foo(userid number, pageid number, dummy number);
Table created
SQL> CREATE OR REPLACE PROCEDURE follow(p_userid NUMBER, p_pageid NUMBER) IS
2 BEGIN
3 MERGE INTO foo f
4 USING (SELECT p_userid userid, p_pageid pageid FROM dual) i
5 ON (f.userid = i.userid AND f.pageid = i.pageid)
6 WHEN MATCHED THEN
7 UPDATE SET f.dummy = NULL
8 DELETE WHERE 1 = 1
9 WHEN NOT MATCHED THEN
10 INSERT (userid, pageid) VALUES (i.userid, i.pageid);
11 END;
12 /
Procedure created
The dummy column is needed because the MERGE statement can't update the join column (in the ON clause) and the UPDATE clause is necessary. Running the statement twice will delete the row:
SQL> exec follow(1, 1);
PL/SQL procedure successfully completed
SQL> select * from foo;
USERID PAGEID DUMMY
---------- ---------- ----------
1 1
SQL> exec follow(1, 2);
PL/SQL procedure successfully completed
SQL> select * from foo;
USERID PAGEID DUMMY
---------- ---------- ----------
1 1
1 2
SQL> exec follow(1, 1);
PL/SQL procedure successfully completed
SQL> select * from foo;
USERID PAGEID DUMMY
---------- ---------- ----------
1 2
As far as I know, You can't do it directly. As a workarround, depending of how you lanuch the queries, you can launch two queries in the same sentence using a semicolon as a separator.
Of course, you can always use a stored procedure instead.
However, I don't think that this solutions are good practices. Keep your two queries in the same transaction and call it from the business layer. It will me more mantenible in the future.
Assuming that the Table that you want to add to or remove from is called User_Page.
IF EXISTS (SELECT * FROM User_Page WHERE USerID = #userID and PageID = #PageID)
BEGIN
DELETE FROM User_Page WHERE USerID = #userID and PageID = #PageID
END
ELSE
BEGIN
INSERT INTO User_Page (UserID, PageID) VALUES (#userID, #pageID)
END