Left Outer Join with subqueries? - sql

----------
User
----------
user_ID(pk)
UserEmail
----------
Project_Account
----------
actno
actname
projno
projname
ProjEmpID
ProjEmpMGRID
Where ProjEmpID,ProjEmpMGRID is the user_id and ProjEmpMGRID can be null.
I need to look up the useremail and display the table project_account. I need to query with actNo which has duplicate values.
My query goes like this:
select projno,projname,actno,actname,
(select u.user_email as project_manager from project_account c left outer join users u
on u.user_id = c.ProjEmpID where actno='some no')as project_manager,
(select u.user_email as program_manager from project_account c left outer join users u
on u.user_id = c.ProjEmpMGRID where actno='someno') as program_manager
from project_account where actno='someno'
The error message I get in Oracle:
ora-01427 single row subquery returns
more than one row
As my subquery returns more than one email id, I get this error. As I said, act no is not unique. I could understand the error, but I couldn't figure out the solution. I am doing a left outer join in a subquery because there might be nulls in prog manager id.
Any help would be appreciated.

The error you are getting is that one of your subqueries (either for project_manager or program_manager) is giving you back more than one ID based on your conditions. This kind of makes sense, since multiple project accounts could have the same "actno" since you haven't specified that as a Primarky Key (pk)
furhter, rather than using subqueries, just join directly to the user tables to find the IDs
select projno,projname,actno,actname,
project_user.user_email as project_manager,
program_user.user_email as program_manager
from project_account
left join User as project_user
on project_account.ProjEmpID = project_user.user_id
left join User as program_user
on project_account.ProjEmpMGRID = program_user.user_id
where actno='someno'

What about something like:
select c.projno, c.projname, c.actno, c.actname, u.user_email as project_manager, us.user_email as program_manager
from project_account c
left outer join users u
on u.user_id = c.ProjEmpID
left outer join users us
on us.user_id = c.ProjEmpMGRID
WHERE actno = 'someno'
This way you aren't running subqueries and returning multiple results and trying to store them as one value.

Why don't you simply use this?
select projno, projname, actno, actname, (select user_email from users where user_id = pa.projempid), (select user_email from users where user_id = pa.projempmgrid)
from project_account pa

Related

Select Count Distinct the value to get unique data

i'm very new in sql and dont have an idea for this even simple one.
table 1 bos_report_users contain user_id,dept,branch_code table 2 bos_report_access contain user_id,report_id
i would like join this table so the result should be something like this
dept | user_id|report_id|.
this is what i have done and result is not what i'm expected.
SELECT A.USER_ID,B.REPORT_ID
FROM(SELECT DISTINCT DEPT FROM BOS_M_USERS WHERE DEPT='FINANCE'),BOS_REPORT_ACCESS B ,BOS_M_USERS A
WHERE A.USER_ID='SLTAM'
kindly assist me everyone. thanks for helping.
The join is performed through the shared column user_id
SELECT
u.user_id, u.dept, u.branch_code
, a.report_id
FROM bos_report_users u
INNER JOIN bos_report_access a ON u.user_id = a.user_id
WHERE u.user_id = 'SLTAM'
ORDER BY u.dept, u.user_id
alias "u" = users
alias "a" = access

SQL Where on different table

SELECT * FROM student_mentor sm INNER JOIN users u
ON sm.student_id = u.user_id
WHERE sm.teacher_id = $teacher_id
Teacher_id being the session id,
I want to see all the students that have the same mentor.
Right now if I run this I just see all of the students twice, maybe one of you knows why?
My db scheme
You are not specifying on which columns you want to do the join, so you're getting a cross reference where all records are joined to all records.
You should do something like (not sure about your column names):
SELECT * FROM student_mentor sm INNER JOIN users u
ON sm.student_id = u.user_id
WHERE sm.teacher_id = $teacher_id

SQL QUERY data reading

I have two table country and Users. I want to view the country name which have user disabled. So i wrote query for this.
SELECT DISTINCT cntr_id,cntr_name FROM
(SELECT COUNTRY.cntr_id, COUNTRY.cntr_name, USERS.user_enabled,
USERS.user_name, USERS.user_id
FROM COUNTRY INNER JOIN Users
ON COUNTRY.cntr_id = USERS.cntr_id
)
AS TAB where user_enabled = 0
My questions are :
Is this inner query?
will the query fetch all the countries (include user enabled) from the database before running outer query?
Is there any other method to select?
Yes it's an inner Query and will fetch what you need, but you don't need your outer SELECT query. You could just do it like:
SELECT DISTINCT COUNTRY.cntr_id, COUNTRY.cntr_name
FROM COUNTRY INNER JOIN Users
ON COUNTRY.cntr_id = USERS.cntr_id
WHERE USERS.user_enabled = 0
Yes, that is inner query.
Yes, inner query will fetch all the countries (including user enabled). Outer query will remove those records later.
You don't have to use outer query for this.
SELECT DISTINCT C.cntr_id, C.cntr_name
FROM COUNTRY C INNER JOIN
Users U ON C.cntr_id = U.cntr_id
WHERE U.user_enabled=0
OR
SELECT C.cntr_id, C.cntr_name
FROM COUNTRY C INNER JOIN
Users U ON C.cntr_id = U.cntr_id
WHERE U.user_enabled=0
GROUP BY C.cntr_id, C.cntr_name
To answer your question,
Yes It is inner and outer two queries.
The inner query will fetch the all rows which satisfy the join condition.
Yes there is other method to select where you can directly apply the filter in inner query and remove the outer select.
SELECT COUNTRY.cntr_id, COUNTRY.cntr_name, USERS.user_enabled,
USERS.user_name, USERS.user_id
FROM COUNTRY INNER JOIN Users
ON COUNTRY.cntr_id = USERS.cntr_id
WHERE
USERS.user_enabled = 0

Using binary logic in PostgreSQL JOIN queries

I've got 3 tables that look vaguely like this:
Users
----------
UserID
Name
Phone
User Groups
-----------
GroupID
Activity
Group Membership
---------------
UserID
GroupID
Independent Actives
-------------------
UserID
Activity
The idea is that a user can perform an activity either as part of a group or on their own. What I want to do is return all the people that partake in a certain activity. What I have been able to write so far lets me return all the users which are in groups that undertake that activity. What I want to add to this is the ability to see the people that do the activity independently. This is what I have so far:
SELECT
users.name, users.phone, user_groups.activity
FROM users
INNER JOIN group_membership ON group_membership.userID = users.userID
INNER JOIN user_groups ON user_groups.groupID = group_membership.groupID
WHERE user_groups.activity = 'Knitting';
The above bit works fine and it shows all of the users that are part of groups that do knitting, but I also want it to show all the users that are knitting independently. This is what I have attempted to add:
SELECT
users.name, users.phone, user_groups.activity
FROM users
INNER JOIN group_membership ON group_membership.userID = users.userID
INNER JOIN user_groups ON user_groups.groupID = group_membership.groupID
INNER JOIN independent_activity ON independent_activity.userID = users.userID
WHERE user_groups.activity = 'Knitting' OR independent_activity.activity = 'Knitting';
The problem here is the syntax, I understand the algorithm that I'm trying to do but I don't know how to transfer it into sql and so any help is appreciated.
You could use a UNION in this case
SELECT users.NAME
,users.phone
,user_groups.activity
FROM users
INNER JOIN group_membership ON group_membership.userID = users.userID
INNER JOIN user_groups ON user_groups.groupID = group_membership.groupID
WHERE user_groups.activity = 'Knitting'
UNION
SELECT users.NAME
,users.phone
,independent_activity.activity
FROM users
INNER JOIN independent_activity ON independent_activity.userID = users.userID
WHERE independent_activity.activity = 'Knitting';
You also might want to lookup the differences between a UNION and a UNION ALL and decide the one that suites your requirement.
You've got a working answer from SoulTrain. However, for completeness sake I'd like to mention that you don't have to join all those tables. (You could use outer joins here and remove duplicate matches with DISTINCT, but that's not necessary. You don't have to query the users table twice either. And you don't need UNION for doing the distinct job.)
Simply select from the one table you want to display data from, i.e. the users table, and then use EXISTS or IN to get only those users that are either in one set or another.
select name, phone
from users
where userid in
(
select userid
from independent_actives
where activity = 'Knitting'
)
or userid
(
select userid
from group_membership
where groupid in (select groupid from user_groups where activity = 'Knitting')
)

SQL QUERY to get Count of particular column between two Range of Dates

Here I have a doubt regarding sql query.
In this scenario I have a table called tblcrime : where we will get the sum(crime) here I track MainID and sum(crime) query will be like this :
SELECT sum(o.crimeID) as crimeNumber,u.UserID
from tblcrime o
inner join tblSubContractor ts on
o.MainID=ts.SubContractorID
from here I will chk the tblUSER with these subcontractorID :
inner join tblUser u on
u.SubContractorID=ts.SubContractorID
and my doubt is that up to here I will get the total sum of crime and appropriate userid., for e.g.
UserID : 520 Totalcrime:6000
but there is another table called tblAudit where we will get logondate and userid, which is tracking here.. so I want to display crime based on userlogin(userid) ...since last login. So that when user login it shows in a jquery notification that "60 crimes has been done since last login".
I want help in query format.
I'm not sure, if I understand your question right, but may this be, what you are looking for?
SELECT sum(o.crimeID) as crimeNumber,u.UserID
from tblcrime o
inner join tblSubContractor ts on o.MainID=ts.SubContractorID
inner join tblUser u on u.SubContractorID=ts.SubContractorID
where
u.UserID = theOneYouAreLookingFor
AND crimedate >= lastLogOn
GROUP BY u.UserID
Firstly, I suspect that the call to the SUM function should really be to COUNT. The former adds the values of the specified column together, whereas the latter gives you a row count.
Secondly, does your tblcrime table store the date that crimes are added? I'll assume it does, let's call the column DateAdded. The following query should work:
SELECT COUNT(o.crimeID) AS crimeNumber,
u.UserID
FROM tblcrime o
INNER JOIN tblSubContractor ts on o.MainID = ts.SubContractorID
INNER JOIN tblUser u on u.SubContractorID = ts.SubContractorID
INNER JOIN tblAudit a on a.userid = u.UserID
WHERE a.logondate < o.DateAdded
GROUP BY u.UserID
You could find the max auditdate for that user:
SELECT sum(o.crimeID) as crimeNumber,u.UserID
from tblcrime o
inner join tblSubContractor ts on
o.MainID=ts.SubContractorID
inner join tblUser u on
u.SubContractorID=ts.SubContractorID
where o.crimeDate >= (select max(auditdate) from tblAudit where UserID = #UserID)