I have two tables Login table and userinfo table. UserInfo table is primary key(UserId) table and login table is foreign key(UserId) table. So my problem is when i insert data in login table value of userid column should come from Userinfo table and value of other columns of log in table like username and password should be inserted directly . Is it possible in single insert statement.
i did the following but it didnt work
insert into login(Userid,username,password)
values(select max(userid) from userinfo,sumit,sumit123)
insert into login(Userid,username,password)
values((select max(userid) from userinfo),'sumit','sumit123');
insert into login (Userid, username, password)
select max(userid), 'sumit', 'sumit123'
from userinfo
[Please note: while that is syntactically correct, I probably wouldn't do it that way.]
Have you tried using a inner JOIN?
INSERT INTO Insurance (Name)
SELECT Employee.Username FROM Employee
INNER JOIN Project ON Employee.EmployeeID = Project.EmployeeID
WHERE Project.ProjectName = 'Hardwork';
Related
I have a scenario where I have thousands of Ids (1-1000), I need to insert each of these Ids once into a table with another record.
For example, UserCars - has columns CarId and UserId
I want to INSERT each user in my Id WHERE clause against CarId 1.
INSERT INTO [dbo].[UserCars]
([CarId]
,[UserId])
VALUES
(
1,
**My list of Ids**
)
I'm just not sure of the syntax for running this kind of insert or if it is at all possible.
As you write in the comments that my list of Ids is coming from another table, you can simply use select into with a select clause
See this for more information
insert into UserCars (CarID, UserID)
select CarID, UserID
from othertable
In the select part you can use joins and whatever you need, complex queries are allowed as long as the columns in the result match the columns (CarID, UserID)
or even this to keep up with your example
insert into UserCars (CarID, UserID)
select 1, UserID
from dbo.User
if your data exists on a file, you can use BULK INSERT command, for example:
BULK INSERT UserCars
FROM '\\path\to\your\folder\users-cars.csv';
Just make sure to have the same columns structure both in the file and in the table (e.g. CarId,UserId).
Otherwise, follow #GuidoG comment to insert your data from another table:
insert into UserCars (CarID, UserID) select CarID, UserID from othertable
I am using following query on postgres database:
insert into user_settings (google_access_token, google_refresh_token)
select 'google_access_token', 'google_refresh_token' from user
where id = user_id
table user_settings has a field user_id which corresponds to field named id in user table. but this gives the error:
column "user_id" does not exist
Hint: There is a column named "user_id" in table "user_settings",
but it cannot be referenced from this part of the query
you are taking a column in user_settings and inserting into that table with condition.
I think you have to use update statement because your condition is
user .id = user_settings .user_id
I guess you need to do like this :
insert into user_settings (google_access_token, google_refresh_token)
select 'google_access_token',
'google_refresh_token'
from user
where id in (select user_id from user_settings )
You can update a table with out NULLs even if you don't have matching values
update user_settings
set
user_settings.google_access_token='google_access_token',
user_settings.google_refresh_token='google_refresh_token'
from user_settings
inner join user
on user_settings.user_id=user.id
I am trying to make exact copies of data in SQL, with new clientIDs, but keep the existing data in the old client as well. I will be inserting the data into a table with an auto incrementing integer primary key ID. I need to retain the ID's of the Old records and the new records together so I can continue using this mapping as I copy the different table data so I can maintain relationships.
At this point I have the following:
INSERT INTO [dbo].[Driver]
OUTPUT inserted.ID
inserted.Name
inserted.ClientID
SELECT Name,
1234 AS clientID
FROM dbo.Driver
I am wondering if there is a way to also select the old ID of the driver in the Output so I can then insert all of this into a holding table using the OUTPUT. So I need to end up with the following after I perform the insert into the dbo.Driver table so I can also insert these values into a temp table:
NewID
OldID
Name
ClientID
At this point I don't know of a way to pull the Original ID from the original record.
I ended up using MERGE INTO to keep track of the old ID as per the following SO post:
How to use OUTPUT to capture new and old ID?
you can try...
INSERT INTO dbo.Driver (oldID, Name, clientID)
SELECT
B.ID,
A.Name,
1234 AS clientID
FROM dbo.Driver A
LEFT JOIN dbo.Driver B ON A.Name = B.Name AND A.clientID = b.clientID
or maybe just
INSERT INTO dbo.Driver (oldID, Name, clientID)
SELECT
ID,
Name,
1234 AS clientID
FROM dbo.Drive
I'm having a problem trying to insert some values into a table. I made an empty table with the fields
id(primary key)
association_id
resource_id
I have another table with
resource_id
association_id
and another one with
id(coresponding to the association_id in the former one)
image
I want to insert the resource_id and association_id from the first populated table, where the image field of the coresponding id from the last table is not empty.
I tried this:
INSERT IGNORE INTO `logo_associations` (``,`association_id`,`resource_id`)
SELECT
``,
`a`.`association_id`,
`a`.`resource_id`
FROM doc24_associations_have_resources a
Join doc24_associations An on a.association_id = An.id
WHERE An.image<>''
but it does not work
Try this:
INSERT INTO logo_associations (association_id, resource_id)
SELECT a.association_id
,a.resource_id
FROM doc24_associations_have_resources a
LEFT JOIN doc24_associations an ON a.association_id = an.id
WHERE an.image IS NULL -- check for null with left join
This is valid for SQL Server. You do not need to select and insert the first column as it is an identity as you mention.
My experience is based on SQL Server but the SQL may be very similar
INSERT INTO DestinationTable
(association_id, resource_id)
SELECT LNK.assocication_id,
LNK.resource_id
FROM LinkTable AS LNK
INNER JOIN ImageTable AS IMG ON IMG.id = LNK.association_id
AND IMG.image IS NOT NULL
Above I assume the following:
Tables are named DestinationTable, LinkTable, and ImageTable respectively
In DestinationTable the primary key (id) is auto generated
So I am revising for an exam and have struck a big rock in the SQL river (or waste ground)
I made the following tables and inserted the following data:
create table Permissions
(
fileName VARCHAR(40),
userID VARCHAR (16),
type VARCHAR(10),
startdate DATE,
duration NUMBER (5),
constraint Pri_key PRIMARY KEY (userID,fileName)
);
create table Files
(
name VARCHAR(20),
fsize INT,
numberofpermissions INT,
constraints PRI_KEY2 PRIMARY KEY (name)
);
create table Users
(
id VARCHAR(20),
password VARCHAR (20),
constraint Pri_key3 PRIMARY KEY (id)
);
-- after all tables create:
alter table Permissions
add constraint Forn_key FOREIGN KEY (userID) REFERENCES Users(id)
INITIALLY DEFERRED DEFERRABLE;
alter table Permissions
add constraint Forn_key2 FOREIGN KEY (filename) REFERENCES Files(name)
INITIALLY DEFERRED DEFERRABLE;
insert into Permissions VALUES ('Agenda','Jones','read','19-JAN-10',30);
insert into Permissions VALUES ('Agenda','Chun','read','19-JAN-10',30);
insert into Permissions VALUES ('Agenda','Rashid','write','17-JAN-10',50);
insert into Permissions VALUES ('Finance','Chun','write','05-DEC-09',50);
insert into Permissions VALUES ('AnnualReport','Jones','write','12-DEC-09',50);
insert into Users VALUES ('Jones', 'duck');
insert into Users VALUES ('Chun', 'tiger');
insert into Users VALUES ('Adams', 'shark');
insert into Users VALUES ('Rashid', 'puma');
insert into Files VALUES ('Agenda', 32, 3);
insert into Files VALUES ('FinanceTables',645, 0);
insert into Files VALUES ('Finance', 120, 1);
insert into Files VALUES ('AnnualReport', 1205, 1);
commit;
I Am now trying to write a SQL command to display for each user who has
permissions for files of a total size of more than 50: the user’s
id, the total size of all the files the user has permissions for, and
the user’s password.
Here is what I have so far but when i try to add anything in to get the password, SQL+ throws up a hissy fit and there will be a hole in my screen soon!
SELECT permissions.userID, sum(fsize) AS Totalsize
FROM files, permissions
where permissions.filename = files.name
group by permissions.userid
having SUM(fsize) > 50;
In oracle, you need to specify the entire group by
SELECT permissions.userID, users.password, sum(fsize) AS Totalsize
FROM files, permissions, users
where permissions.filename = files.name
and users.id = permissions.userID
group by permissions.userid, permissions.password
having SUM(fsize) > 50;
This is different from MySQL where the group by can be implied, but this is more correct.
Join against the user table, and add the password to the group by clause:
SELECT permissions.userID, users.password, sum(fsize) AS Totalsize
FROM files, permissions, users
where permissions.filename = files.name
and users.id = permissions.userID
group by permissions.userid, users.password
having SUM(fsize) > 50;
Use the JOIN syntax. It complies with ANSI SQL. Joining using WHERE is an old syntax that should not be used any more.
SELECT
u.id AS userid, u.password, SUM(f.fsize) AS Totalsize
FROM
users u
INNER JOIN permissions p
ON u.id = p.userID
INNER JOIN files f
ON p.filename = f.name
GROUP BY
u.id, u.password
HAVING
SUM(f.fsize) > 50;
Note that conditions based on aggregation functions must be placed in the HAVING clause. The difference between the WHERE and the HAVING clause is, that WHERE is executed before grouping and HAVING is executed after grouping.
Also, the GROUP BY clause must contain all the expressions from the SELECT-list that don't have an aggregation function.
This should work:
SELECT Users.id, Users.password, Totalsize
FROM Users
INNER JOIN
(SELECT userId, SUM(fSize) AS TotalSize
FROM permissions
INNER JOIN files ON permissions.filename = files.name
group by permissions.userid
having SUM(fsize) > 50) t ON t.userId = Users.Id
This could be done without the inner join of course, however if you gonna need more fields this makes it easier to add them without having to add the extra fields to the group by clause.