Create a view that joins data from other table multiple cells into one oracle sql - sql

I need to create a view that combines two tables (game and developer) together and selects gameID gameName and gameDeveloper from the game table and repaces gameDeveloper with firstname and lastname (from developers table) into one column. gameDeveloper is the same as developerID, but it is not a foreign key yet on purpose. I want to select only firstname and lastname from the row that contains the matching developerID and combine them in one column in my new view. Heres what I have:
CREATE TABLE game (
gameID varchar(3) PRIMARY KEY NOT NULL,
gamenameName varchar(30) NOT NULL,
gameDeveloper varchar(3) NOT NULL
);
INSERT INTO game VALUES (1,'RDR2',2);
INSERT INTO game VALUES (2,'GTAV',7);
INSERT INTO game VALUES (3,'PUBG',9);
/
CREATE TABLE developers (
developerID varchar(3) PRIMARY KEY NOT
NULL,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
gameID varchar(3) NOT NULL,
CONSTRAINT fk_game
FOREIGN KEY (gameID)
REFERENCES game (GameID)
);
INSERT INTO developers VALUES
(1,'Patrick','Kane',1);
INSERT INTO developers VALUES
(2,'Jonathan','Toews',1);
INSERT INTO developers VALUES
(3,'Alex','Debrincat',1);
INSERT INTO developers VALUES
(4,'Andrew','Shaw',2);
INSERT INTO developers VALUES
(5,'Alex','Nylander',2);
INSERT INTO developers VALUES
(6,'Oli','Maata',2);
INSERT INTO developers VALUES
(7,'Calvin','DeHaan',2);
INSERT INTO developers VALUES
(8,'Brandon','Saad',3);
INSERT INTO developers VALUES
(9,'Corey','Crawford',3);
INSERT INTO developers VALUES
(10,'Connor','Murphy',3);
/
CREATE OR REPLACE VIEW chairs AS
SELECT firstname, lastname
FROM developer
INNER JOIN
I'd like the final table to look something like this with the mapped and combined last cell but I am so lost on what to do.. I figured an inner join would be best?

You can do something like this - JOIN is the equivalent to INNER JOIN but you can be explicit.
CREATE VIEW chairs
AS
SELECT
g.gameID
,g.gamenameName
,d.fname + ' ' + lname AS gameDeveloper
FROM game g
JOIN developers d
ON g.gameDeveloper = d. developerID

Related

Insert into table1 using data from staging_table1 and table2, while using staging_table1 to get the data from table2

Goal: Insert all data into a table from staging table. Each piece of data in the staging table has 2 names which can be found in a separate table. By using the 2 two names, I want to find their respective IDs and insert them into the foreign keys of the main table.
Question: How do I insert the data from a staging table into a table while using data from the staging to query IDs from a separate table?
Example tables:
TABLE location:
id int PRIMARY KEY,
location varchar(255) NOT NULL,
person_oneID int FOREIGN KEY REFERENCES people(person_id),
person_twoID int FOREIGN KEY REFERENCES people(person_id)
TABLE staging_location:
id int PRIMARY KEY,
location varchar(255) NOT NULL,
p1_full_name varchar(255) NOT NULL,
p2_full_name varchar(255) NOT NULL
TABLE people:
person_id int PRIMARY KEY,
first_name varchar(255) NOT NULL,
last_name varchar(255) NOT NULL,
full_name varchar(255) NOT NULL,
This question was the closest example to what I have been looking for. Though I haven't been able to get the query to work. Here is what I've tried:
INSERT INTO location(id,location,person_oneID,person_twoID)
SELECT (l.id,l.location,p1.person_oneID,p2.person_twoID)
FROM staging_location AS l
INNER JOIN people p1 ON p1.full_name = l.p1_full_name
INNER JOIN people p2 ON p2.full_name = l.p2_full_name
Additional info: I would like to do this in the same insert statement without using an update because of the number of locations being inserted. I'm using staging tables as a result of importing data from csv files. The csv file with people didn't have an ID field, so I created one for each person by following steps similar to the first answer from this question. Please let me know if any additional information is required or if I can find the answer to my question somewhere I haven't seen.
Use this code even though I do not know what your data structure is and a duplicate field may be inserted
INSERT INTO location(id,location,person_oneID,person_twoID)
SELECT (l.id,l.location,p1.person_id as person_oneID,p2.person_id as person_twoID)
FROM staging_location AS l
INNER JOIN people p1 ON p1.full_name = l.p1_full_name
INNER JOIN people p2 ON p2.full_name = l.p2_full_name

When inserting into one table, insert into others with the same values

I have 3 tables:
users, contact and pay_roll.
All of the tables share the column user_id which is the primary key and is auto incrementing on all of them, when I insert a new user into the table "users", is there a way to add a blank row to both contact and pay_roll to then be updated later?
My SQL query so far:
INSERT INTO dbo.users (fName, lName) VALUES ('Kieron', 'Oates')
You can use output clause of insert and insert into another table as below:
declare #otheruser table (fname varchar(10), lname varchar(10))
declare #user table (fname varchar(10), lname varchar(10))
insert into #user(fname, lname)
output inserted.fname, inserted.lname into #otheruser
values ('Kieron', 'Oates')
select * from #otheruser
select * from #user
For empty rows you can use as below:
create table #contact (userid int, fname varchar(10), addr varchar(10))
create table #user (userid int identity(1,1), fname varchar(10), lname varchar(10))
create table #pay_roll (userid int, pay money)
insert into #user(fname, lname)
output inserted.userid, null as fname, null as addr into #contact
values ('Kieron', 'Oates')
You're doing it wrong; your schema is fundamentally flawed. The "child" tables contact and payroll are dependent on the user table and should NOT have an identity column used as the foreign key to user. Remove the identity property from these columns. And since it is apparent that you want to create a 1:1 relationship between user and each child table, then the user column in contact and payroll should be both primary key and foreign key.
And no - you do not add "blank" rows to be filled in later. Why? For one, you cannot really distinguish between a "blank" row and a non-blank row without making assumptions about the content of columns. This approach will only lead to tears and many many long hours of work at a later date.

SQL auto-validating data when adding it to row

My SQL code is as follows:
CREATE TABLE personsdb
(personID int IDENTITY(1,1) NOT NULL,
personName varchar(50) NOT NULL,
associatedWith varchar(50) NOT NULL,
CONSTRAINT pk_persondb PRIMARY KEY (personID),
CONSTRAINT uq_persondb UNIQUE (associatedWith))
INSERT INTO personsdb
(personID, personName, associatedWith)
VALUES
('John', 'Mary'),
('Jack', 'Maggie'),
('Jeff', 'Marie')
I have a UNIQUE Constraint on the 'associatedWith' column, as I want to make sure that a person in personName can only be associated with one person in associatedWith, i.e. Mary could not be associated with Jeff because Mary is already associated with John.
My query relates to inserting the next row of the table. I want to insert 'Mary' into the personName column, but need a rule that autopopulates or only allows 'John' to be populated in the corresponding 'associatedWith' field, as a person can only be associated with one other person, and as John is already associated with Mary, when Mary is entered into the table, she should automatically be associated with John.
I'm relatively new to SQL but I'd like to figure it out as much as possible myself - if you could hint at a way to do this (in layman's terms) I'd be grateful so that I can go and research and learn how to do this.
Thanks very much in advance for your help.
David
This is a unary relationship which you cannot implement using foreign keys. You'll have to use a trigger. See below for full implementation.
CREATE TABLE dbo.Person(PersonId int not null primary key identity(1, 1), PersonName varchar(20) not null, AssociatedWith varchar(20));
GO
create trigger dbo.AssociationConstraint
ON dbo.Person
FOR INSERT, UPDATE
AS
IF (EXISTS(SELECT TOP(1) 1 FROM inserted i INNER JOIN dbo.Person p on i.PersonName = p.AssociatedWith)
OR EXISTS(SELECT TOP(1) 1 FROM inserted i INNER JOIN dbo.Person p on i.AssociatedWith = p.PersonName))
BEGIN
RAISERROR('Person is already part of a relationship', 16, 1);
ROLLBACK TRANSACTION;
END
GO
insert into dbo.Person(PersonName, AssociatedWith) values('John', 'Mary'), ('Jack', 'Maggie'), ('Jeff', 'Marie');
--this will error
insert into dbo.Person(PersonName, AssociatedWith) values('Mary', 'Jack');

SQL datable query to insert multiple column values

How to add multiple values in a single column of table in SQL? My table looks like this:
Create table emp
(
id number(5),
name varchar(25),
phone varchar(25)
);
Now I want to add values and multiple phones in the phone column. How to do that? I tried using
insert into emp values (id, name, phone)
values (1, lee, (23455, 67543));
but this is not working
Use two insert statements instead
insert into emp values (id, name,phone) values (1,'lee','23455');
insert into emp values (id, name,phone) values (1,'lee','67543');
or If you want to store both the values in single row
insert into emp values (id, name,phone) values (1,'lee','23455,67543');
Here table is not normalised. You either need to store Phone Number info in separate table or use two different column in same table.
Try changing you table design like this.
EMP table
CREATE TABLE emp
(
emp_id INT IDENTITY(1, 1) PRIMARY KEY,
name VARCHAR(25)
);
PhoneNumber Table
CREATE TABLE PhoneNumber
(
phoneno_id INT IDENTITY(1, 1),
emp_id INT,
Phone_Number int,
Cell_Number Int,
FOREIGN KEY (emp_id) REFERENCES emp(emp_id)
)
Note : Auto increment syntax may differ based on the database you are using.
The proper and only real well-designed way to do this in a relational setting is to use a separate table for your phones (this is in SQL Server specific syntax - it might be slightly different, depending on which concrete database system you're using):
Create table emp
(
id INT PRIMARY KEY,
name varchar(25)
)
create table phone
(
phoneId INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
empid INT NOT NULL,
phone varchar(25) NOT NULL,
CONSTRAINT FK_Phone_Emp
FOREIGN KEY(empid) REFERENCES dbo.emp(id)
);
and then you insert the employee data into emp :
insert into emp(id, name)
values (1, lee);
and the phones into phone:
insert into phone(empid, phone) values(1, 23455);
insert into phone(empid, phone) values(1, 67543);
With this setup, you have proper normalization for the database, and you can store as many phones as you like, for each employee.

need help in primary key and foreign key

I need help in auto populating the primary key values in foreign key table while inserting data in foreign key table. For Example: I have created table:
create table Patient
(
PatientId int IDENTITY(1,1) primary key,
FirstName varchar(50),
SurName varchar(50),
Gender char(20),
)
Say 5 rows are there in this Patient Table:
Say First Row value is: 1, Priya, Kumari, Female
I have created the Guardians Table:
create table Guardians
(
GuardiansId int identity(1,1) primary key,
PatientId int foreign key references Patient(PatientId),
FirstName varchar(50),
SurName varchar(50),
Gender char(20),
RelationToPatient varchar(50),
)
In this table Insert operations are like this:
insert into Guardians(FirstName, SurName, Gender,RelationToPatient)values('Sumit','Kumar','Male','Wife')
While selecting the Guardians Table PatientId showing NULL values: My query is while inserting the values in Guardians Table PatientId should be auto Populated which will come from Patient Table...
My second problem is: How to create the Identity column as varchar. For example: suppose I want to increment my Guardians Table with 'GRD0001', 'GRD0002', 'GRD0003' like this...
Thanks,
S.D
Your question is not very clear - what exactly do you want to do??
When you insert something into the Guardians table, you want to automatically also insert it into the Patients table? I don't quite follow. Can you make a complete example, maybe??
If you need to capture the insert IDENTITY value from the Patient table, do this:
DECLARE #NewPatientID INT
INSERT INTO dbo.Patient(fields) VALUES(.......)
SET #NewPatientID = SCOPE_IDENTITY()
INSERT INTO dbo.Guardians(PatientId, ......) VALUES(#NewPatientID, ......)
As for your second question: leave you GuardiansId IDENTITY as it is (only an INT column can be an IDENTITY and you want to keep that - trust me!) and add a computed column to your table:
ALTER TABLE dbo.Guardians
ADD GuardianIDWithPrefix AS
'GDR' + RIGHT('0000' + CAST(GuardiansId AS VARCHAR(4)), 4) PERSISTED
Since it's a PERSISTED field, you can even index on it and use it like a normal field in every respect.
That should do the trick!