SQL complex select statement in stored procedure - sql

I have 3 tables in my database;
InfoTable,
FriendTable,
UsersTable
and these are their columns:
InfoTable
Uid int,
Username varchar(256),
Address varchar(256),
FriendTable
Fid int,
UserName varchar(256),
FriendUserName varchar(256),
Status varchar(10)---Default value:'false'
UsersTable
Uid int,
FirstName varchar(256),
LastName varchar(256),
Username varchar(256)
I have to achieve all information of friends of that username. I am getting using this query,
SELECT *
FROM InfoTable
WHERE username IN
(SELECT FriendUserName
FROM FriendTable
WHERE username = #UserName AND status='true')
Now I have to add his/her FirstName and LastName from users table in the same query.
How can I achieve this in one complete query?

SELECT friend.*
from InfoTable info
inner join FriendTable friend on info.username=friend.FriendUserName
--inner join UsersTable user1 on info.Uid=user1.Uid
--(In case you want columns from UsersTable)
where info.username=#UserName
friend.status='true'
Here is good article for JOIN

SELECT info.*, frnd.*, usr.*
from InfoTable info
INNER join FriendTable frnd on frnd.FriendUserName = info.username
INNER join usersTable usr on usr.Uid=info.Uid
This will give you all details of all table. And you can add your conditions in the above query like ( and frnd.username=#UserName and frnd.status='true').

You just need to create a join query like
select i.*,f.*,u.* from infitable as i join friendtable as f
on i.username = f.friendusername join usertable as u on i.uid = u.uid
where i.username=#UserName and
f.status='true';
Here i am selecting all tables value you can select as per your own need.
For Knowledge about joins Click Here
Hope it works.

TRY THIS
SELECT it.*, ut.FirstName, ut.LastName
FROM InfoTable it
LEFT OUTER JOIN UsersTable ut
ON it.Uid = ut.Uid
WHERE it.username IN
(SELECT FriendUserName
FROM FriendTable
WHERE username = #UserName AND status='true')

Related

Select Statement in SQL inheritance

CREATE TABLE User(
UserID int primary key,
Name varchar,
type int
);
CREATE TABLE Student(
UserID int primary key references User(UserID),
marks int
);
CREATE TABLE Lecture(
UserID int primary key references User(UserID),
salary int
);
Can someone help with with select statement for Student or lecture.
Both Lecture and Student tables are inheriting from User table,So I need to know how insert data and select data from these tables.
To query the tables, this would work:
SELECT u.[Name]
, s.marks
, l.salary
FROM [User] u
INNER JOIN Student s
ON u.UserId = s.UserId
INNER JOIN Lecture l
ON u.UserId = l.UserId;
However, if there are no records in the Student / Lecture tables yet, you should use LEFT Join instead.
As for inserting the data, you would need to use SCOPE_IDENTITY().
Insert into [User] (Name) values ('Melvin')
Get the identity of the UserId
DECLARE #userId INT;
SELECT #userId = SCOPE_IDENTITY ();
INSERT INTO Student
(
UserID
, Marks
)
VALUES
(userId, 5);
Update: Just noticed this was SQL Lite, which I'm not so familiar with, but it looks like it supports last_insert_rowid() instead of SCOPE_IDENTITY (), but you should get the gist of it.
If you want to select Student X:
SELECT *
FROM Student
WHERE UserID = X
If you want to select all Students and their User data, you'll want something like:
SELECT *
FROM User
JOIN Student ON User.UserID = Student.UserID
I don't understand your question but I think you need something like that
select Name, marks
from User as u, Student as s
inner join u.UserID == s.UserID;

select all from table1 with zero entries in table2 in sqlite?

Consider 2 tables, user and contact:
CREATE TABLE user (
id INT,
name VARCHAR(36)
);
CREATE TABLE contact (
id INT,
phone INT,
userID INT
);
INSERT INTO user (id,name) VALUES
(1,'Frank'),
(2,'Henry'),
(3,'John')
INSERT INTO contact (id,phone,userID) VALUES
(1,911,1),
(2,922,2),
(3,933,2)
I am interested in all user entries that do not have any contact.
The outer join of these tables returns 4 results:
SELECT contact.*, user.*
FROM contact
LEFT JOIN user
ON contact.userID = user.id
UNION ALL
SELECT contact.*, user.*
FROM user
LEFT JOIN contact
ON contact.userID = user.id
WHERE contact.userID IS NULL
How do I select all user where contact.userID is null (1 result, in this example)?
This is your second subquery:
SELECT c.*, u.*
FROM user u LEFT JOIN
contact c
ON c.userID = u.id
WHERE c.userID IS NULL;
It does exactly what you want, although I would remove the c.* from the SELECT.

Show correct result with SQL Joins

Firstly, I am newbie to SQL (T-SQL), I would appreciate guidance with this.
I have 3 tables with values created as below.
CREATE Table StudentProject
(ID int identity (1,1) PRIMARY KEY,
ProjectName Varchar (30),
DueDate Date)
CREATE Table StudentName
(ID int identity (1,1) PRIMARY KEY,
StudentName Varchar (30))
CREATE Table StudentWork
(ID int identity (1,1) PRIMARY KEY,
ProjectID int,
StudentID int)
Insert Into StudentProject values
('Omega','1/2/2005'),('KingOmega','1/3/2000'),('Beast','1/6/2007'),
('DeltaMovie','3/7/2008')
Insert into StudentName values
('Roger'),('John'),('James'),('Juliet'),('William')
Insert into StudentWork values
(1,1),(1,2),(2,2),(2,3),(3,3),(3,4),(1,3)
The goal is to produce the below outcome but seems that i cant or i'm sure i'm doing something wrong.
SQL_Outcom
Please help.
SELECT StudentProject.ProjectName, StudentName.StudentName
FROM StudentWork
INNER JOIN StudentProject ON StudentProject.ID = StudentWork.ProjectID
INNER JOIN StudentName ON StudentName.ID = StudentWork.StudentID
You have 3 tables, try to recognize the "master table", then join them to other tables, after joining them you will have access to their columns.
Hello World :)
UPDATE:
In order to confirm Roger always with id 1 and all the other students in StudentName table, you need to use SET IDENTITY_INSERT which guarantee you the ordering of rows.
Instead of :
Insert into StudentName values
('Roger'),('John'),('James'),('Juliet'),('William')
Do this:
SET IDENTITY_INSERT StudentName ON
Insert into StudentName values
(1,'Roger'),(2,'John'),(3,'James'),(4,'Juliet'),(5,'William')
SET IDENTITY_INSERT StudentName OFF
You need to use inner join and in order to match the records related to each others:
Select p.ProjectName, s.StudentName from StudentName s
Inner join Studentwork sw on sw.studentid = s.Id
inner join StudentProject p on p.ID= sw.ProjectId
Order by P.ProjectName desc
You need inner join
Try this :
select s.StudentName,p.ProjectName from StudentName s
inner join StudentProject sp on sp.id= sw.ProjectId
inner join StudentWork sw on sw.studentid = s.id;

How to replace LEFT outer join with INNER join in SQL?

I have a view on which I need to provide cluster Indexing the problem is in order to provide cluster indexing the it should not have any of the left or right outer joins , and I want to replace the LEFT outer join with INNER join , one of the ways which I can think of is to insert a dummy value with lets say -1 in the right table and by doing this even if all the Ids from the left table wont match Ids from the right table in INNER JOIN but since we have inserted -1 in the right table and we are using IsNULL(u.UserId,-1) it should return all the values from the left table but somehow this approach is not working.
create table Users(
UserId int,
UserName nvarchar(255)
)
insert into Users values(1,'sid429')
insert into Users values(2,'ru654')
insert into Users values(3,'dick231')
create table managers
(
caseId int,
CaseName nvarchar(255),
UserId int
)
insert into managers values (100,'Case1',1)
insert into managers values (101,'Case2',2)
insert into managers values (-1,NULL,-1)
select username from users u inner join managers m on m.UserId=IsNULL(u.UserId,-1)
Don't talk about indexes, but I think you could replace LEFT JOIN by INNER JOIN + UNION
select username from users u inner join managers m on m.UserId= u.UserId
UNION ALL
select username from users u WHERE NOT EXISTS (SELECT 1 FROM managers m WHERE m.UserId = u.UserId)
IsNull(u.UserId,-1) doesn't seem right - u.UserId is never null, since the absence of data is in the managers table - in this case, u.UserId will always have a value, but m.UserId might not, so IsNull(u.UserId, -1) won't work.
I'm intrigued to see a better answer, but I don't think you can do that - I think you eventually need to substitute the value conditionally to -1 if it doesn't exist in the other table, like this:
select username from users u
inner join managers m on m.UserId =
case when not exists(select * from managers where UserId = u.UserId)
then -1 else u.UserId end
This has the desired effect, but looking at the execution plan, won't help your performance issue.
You can replace a LEFT OUTER JOIN with an INNER JOIN if you add the missing values in the related table.
It has not worked for you because you have added a -1 value. But the not matching value on your INNER JOIN is a 3, not a null or a -1.
You can do so at runtime with an UNION, no need to permanently create those values as you have tried to do (inserting that -1 value) :
with expanded_managers as (
select CaseId, CaseName, UserId
from managers
union
select null, null, UserId
from users
where not exists (select * from managers where managers.UserId = users.UserId)
)
select UserName, CaseName
from users
inner join expanded_managers on expanded_managers.UserId = users.UserId
if you require only username it should be simple:
select distinct username from users u inner join managers m on m.UserId=u.UserId OR ( m.UserId=-1 AND u.userId = u.userId)
I have cleaned-up this part a bit. I had to guess the logical model, given that you did not specify any constraints.
create table Users (
UserId int not null
, UserName nvarchar(255) not null
, constraint pk_users primary key (UserId)
, constraint ak_users unique (UserName)
);
create table Cases (
CaseId int not null
, CaseName nvarchar(255) not null
, UserId int not null
, constraint pk_cases primary key (CaseId)
, constraint ak_cases unique (CaseName)
, constraint fk_cases foreign key (UserId)
references Users (UserId)
);
insert into Users values(1,'sid429') ;
insert into Users values(2,'ru654') ;
insert into Users values(3,'dick231');
insert into Cases values (100,'Case1',1);
insert into Cases values (101,'Case2',2);
This is mostly self-explanatory, but you have to understand that candidate keys (unique) for the result are: {UserID, CaseId}, {UserName, CaseName}, {UserID, CaseName}, {UserName, CaseId}. Not sure if you were expecting that.
with
R_00 as (
select UserId from Users
except
select UserId from Cases
)
select u.UserId
, u.UserName
, c.CaseId
, c.CaseName
from Users as u
join Cases as c on u.UserId = c.UserId
union
select u.UserId
, u.UserName
, (-1) as CaseId
, 'n/a'as CaseName
from Users as u
join R_00 as r on r.UserId = u.UserID
;
Another version of this, similar to other examples in the post.
select u.UserId
, u.UserName
, c.CaseId
, c.CaseName
from Users as u
join Cases as c on u.UserId = c.UserId
union
select u.UserId
, u.UserName
, (-1) as CaseId
, 'n/a' as CaseName
from Users as u
where not exists (select 1 from Cases as c where c.UserId = u.userId)
;

Insert values from one table to another table and other additional values

I have two tables Users and Friends. I want to copy two ID s for different users from Users table where their names already provided by C# code behind and put them into Friends table with their status column to be stored in one row at Friends table. Here is the query I made:
#id uniqueidentifier,
#username nvarchar(50),
#friendname nvarchar(50),
#friendstatus int
AS
INSERT INTO Friends (MYID,FriendId,ID,FriendStatus)
SELECT Users.ID,Users.ID,#id,#friendstatus
From Users cross join Friends as Friends_1
WHERE (Friends_1.MyID IN
(SELECT ID
FROM Users AS Users_1
WHERE (UserName IN (#username))))
AND (Friends_1.FriendId IN
(SELECT ID
FROM Users AS Users_1
WHERE (UserName IN (#friendname))))
I think this is what you are looking for
INSERT INTO Friends (MYID,FriendId,ID,FriendStatus)
SELECT Users.ID, Users.ID, #id, #friendstatus
From Users
inner join Friends as Friends_1 ON Users.ID = Friends_1.MyID
OR Users.ID = Friends_1.FriendId
WHERE UserName IN (#username, #friendname)
I think you can do it with a simple query like this:
insert into Friends (ID, MYID, FriendId, FriendStatus)
select
newid() ID, -- you can generate a new ID in SQL Server
-- #id ID -- if you generate ID in your c# code:
u1.ID MYID,
u2.ID FriendId,
#friendstatus FriendStatus
from
users u1
cross join
users u2
where
u1.UserName = #username
and
u2.UserName = #friendname;