Basically I have an existing users table, and I need to add a table for user metadata. When a new user is created we generate the default metadata, but for existing users this doesn't exist yet and we need it to.
Essentially add table, loop through users, and insert default data, something like this pseudo-code:
FOR EVERY user IN users
INSERT INTO `meta_data` VALUES (
'generate UUID',
'users UUID from users table'
'2014-12-29 22:57:55',
'2015-01-01 01:39:37',
);
I've dealt with a little bit of mysql but this would be my first any sort of sql script.
Use an INSERT statement with a SELECT in place of the values:
INSERT INTO meta_data
SELECT UUID(), u.uuid, '2014-12-29 22:57:55', '2015-01-01 01:39:37'
FROM users AS u
If you need to do this after you start adding metadata for new users, you can filter them out:
INSERT INTO meta_data
SELECT UUID(), u.uid, '2014-12-29 22:57:55', '2015-01-01 01:39:37'
FROM users AS u
LEFT JOIN meta_data AS m ON u.uuid = m.users_uuid
WHERE m.users_uuid IS NULL
Related
I have an assignment from uni where i need to simulate something like Spotify (without player).
Some context: The thing is i want to make a trigger so that when a new playlist is created (column on table playlist), the creator user (userID) is set as it's first follower. The table followingPlaylist is an intermidiate table that keeps record of which user follows which playlist. On top of that, accounts have 2 types, artists and users (so there is the table accounts that keeps the account info, users and artists that keep the accountID and userID or artistID respectively).
The problem i have is that mysql throws sintax error with this query, if anyone could help i'd be much obliged. This is the query:
CREATE TRIGGER primer_seguidor ON playlists
FOR INSERT AS
INSERT INTO followingPlaylist
(accountID, playlistID)
SELECT
playlists.playlistID, users.accountID FROM playlists
INNER JOIN usuers ON playlists.userID = users.userID;
CREATE TRIGGER primer_seguidor
AFTER INSERT
ON playlists
FOR EACH ROW
INSERT INTO followingPlaylist (accountID, playlistID)
SELECT NEW.playlistID, users.accountID
FROM users
WHERE NEW.userID = users.userID;
PS. Syntax correction only, no logic checking.
PPS. Modelling fiddle
I use my SQL for my app.
Say I have a table of all registered users for my app.
say I have users at hand and I want to filter (or select) from my database the only ones that are registered.
For example my data base have user1,user2......user100
and input user set : user3,user5,user10,user999,user2000 so the output of the query will be : user3,user5 and user 10 only.
Thank you in advance
You seem to want in:
select t.*
from t
where user_id in ('user3', 'user5', 'user10', 'user999', 'user2000')
This will return only the matching users.
The format the user is passing these values is very important here. I am assuming that you have different rows of information. If in that case, you could make use of the below code.
Declare #MyTableVar table
(User_ID VARCHAR(32) primary key)
INSERT #MyTableVar VALUES ('user3')
INSERT #MyTableVar VALUES ('user5')
INSERT #MyTableVar VALUES ('user10')
INSERT #MyTableVar VALUES ('user999')
INSERT #MyTableVar VALUES ('user2000')
SELECT *
FROM #MyTableVar
WHERE User_ID NOT IN (SELECT USER_ID FROM database.schema.table_name)
If your user is passing values in the same row you can convert them to multiple rows using CROSS APPLY. Example can be seen here
Kartheek
I have users from many external sources which I try to map to internal userId, so the table I have is:
userId, externalSourceId, externalUserId
In my code, I'm getting externalSourceId and externalUserId and want to get the userId from the database, if exists, otherwise, create one and return the newly created value. I need this action to be atomic because several processes may try to do the same thing at the same time, so I wished only the first time will create a userId.
In pseudo code it will look like that:
u = find user with (externalSourceId, externalUserId)
if no u:
2.1. u = create new user with (externalSourceId, externalUserId) and random userId
return u
INSERT INTO `users`
(`externalSourceId`, externalUserId)
VALUES( 10, 100)
ON DUPLICATE KEY
UPDATE userId=userId
You can also use insert ignore. You can read more about DUPLICATE KEY versus INSERT IGNORE
INSERT IGNORE INTO test (externalSourceId,externalUserId) VALUES (23,32);
SELECT userId FROM test WHERE externalSourceId=23 AND externalUserId=32;
You can use this if externalSourceId and externalUserId are defined unique.
I have read all most of the answers and even tried them. But this is my case where I'm inserting record from a .csv file into the database. I want to insert a record if it does not exist.
Here is my query
INSERT INTO retailer(retailerCode, contact, shopName, address,
retailerType, lastVisit, officeID, createDate)
VALUES ('', '$emapData[1]', '$emapData[2]', '$emapData[3]',
'$emapData[4]', '', '$id', CURDATE())
WHERE NOT EXISTS (SELECT retailerID
FROM retailer
WHERE contact = '$emapData[1]')
Here $emapData is a PHP array that saves the records of the .csv file. The insert statement works fine without this part
WHERE NOT EXISTS (SELECT retailerID
FROM retailer
WHERE contact = '$emapData[1]')
But my goal is not achieved.
You cannot use WHERE with INSERT in that way.
What you can do:
As #Sylwit suggested, create unique index on contact and use INSERT IGNORE
alter table retailer add unique (contact)
Use INSERT INTO SELECT syntax
INSERT INTO retailer(retailerCode,contact,shopName,address,retailerType,lastVisit,officeID,createDate)
select '','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','','$id', CURDATE()
from retailer
WHERE NOT EXISTS (SELECT retailerID FROM retailer WHERE contact='$emapData[1]')
I'm using MySQL Stored Procedures and I want to insert some rows from a table's database to another table's database through a stored procedure. More specifically from database "new_schema", table "Routers" and field "mac_address" to database "data_warehouse2", table "dim_cpe" and field "mac_address".
This is the code I used in the first insertion, that worked perfectly.
insert into data_warehouse2.dim_cpe (data_warehouse2.dim_cpe.mac_address, data_warehouse2.dim_cpe.ssid)
(select new_schema.Routers.mac_address, new_schema.Routers.ssid from new_schema.Routers, data_warehouse2.dim_cpe);
Now I have more rows in the table "Routers" to be inserted into "dim_cpe" but, since there are rows already there, I want just to insert the new ones.
As seen in other posts, I tried a where clause:
where new_schema.device_info.mac_address != data_warehouse2.dim_cpe.mac_address
and a:
on duplicate key update new_schema.Routers.mac_address = data_warehouse2.dim_cpe.mac_address"
Both didn't work. What's the best way to do this?
Thanks in advance.
You could leave the source table out of the from clause, and use a not exists clause instead:
where not exists
(select mac_address from dim_cpe mac_address = new_schema.Routers.mac_address
and ssid = new_schema.Routers.ssid)
Or you could left join and check whether the fields from dim_cpe are null:
insert into data_warehouse2.dim_cpe
(data_warehouse2.dim_cpe.mac_address, data_warehouse2.dim_cpe.ssid)
(select new_schema.Routers.mac_address, new_schema.Routers.ssid
from new_schema.Routers
left join data_warehouse2.dim_cpe on
new_schema.Routers.mac_address = data_warehouse2.dim_cpe.mac_address
and new_schema.Routers.ssid = data_warehouse2.dim_cpe.ssid
where dim_cpe.mac_address is null and dim_cpe.ssid is null);
Edit to say this is a general SQL solution. I'm not sure if there's a better MySql-specific approach to this.
Edit to show your query:
insert into data_warehouse2.dim_cpe (mac_address, ssid)
select new_schema.Routers.mac_address, new_schema.Routers.ssid
from new_schema.Routers where not exists
(select data_warehouse2.dim_cpe.mac_address from data_warehouse2.dim_cpe
where data_warehouse2.dim_cpe.mac_address = new_schema.Routers.mac_address
and data_warehouse2.dim_cpe.ssid = new_schema.Routers.ssid);