Help me for a simple SQL query

Status
Not open for further replies.

Calimero!

Seniorius Lurkius
6
Hello to all,

I have to design a SQL query on an Oracle 10 DB.
I want to do it in an elegant way and avoid, if possible, using sub-queries and in the most portable way possible.

Basically it's query involving 3 tables :

- A MEMBERS table. This table holds information about persons.
The relevant fields are first name, last name, member id (numeric auto-generated primary key), beginning of membership (a date), end of membership (date).
None of these fields can be null.

- A SESSIONS table. A session is a meeting between MEMBERS. It has an id (numeric auto-generated primary key), a date, that can't be null,
and other irrelevant information.

- Since sessions typically involve several MEMBERS, and a member can participate in several SESSIONS, there is an association table MEMBERS_SESSIONS
that has the member id, sessions id, (of course the combination of the two must be unique across the table) and various other irrelevant fields.

What I have to is to allow users to add members to an existing session, whose id is known.

For this I have to generate a list of all the members that satisfy three conditions :

-they are not currently a member of that session.
-their beginning of membership is before, or equal to the session date.
-their end of membership is after or equal to the session date.

I couldn't figure out a way to do this without sub-queries, and even the query I obtained looks clumsy because the session id is mentioned 3 times, once for each condition.
Is there a way to do this using only SQL operators like LEFT JOIN, RIGHT JOIN, MINUS, INTERSECT, etc. ? I haven't touched SQL for 3 years and could'nt figure it out.

Thanks in advance.
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
LimpBagel":12vjtktn said:
Code:
SELECT m.*
FROM Members m
LEFT JOIN Member_Sessions ms
  ON ms.MemberID = m.ID
 AND ms.SessionID = @SessionID
WHERE ms.SessionID IS NULL

What if the member is in sessions other than the one specified? That query will only return members that have NO sessions. It also ignores the time constraints.


Someone else can likely write this cleaner than I can, but this will get you exactly what the OP wants.
Code:
SELECT
    m.*
FROM
    members m
WHERE
    m.member_id NOT EXISTS(SELECT 1 FROM members_sessions WHERE session_id = @sessionID and member_id = m.member_id)
    AND m.membership_start <= (SELECT session_date FROM sessions WHERE session_id = @sessionID)
    AND m.membership_end >= (SELECT session_date FROM sessions WHERE session_id = @sessionID)
;

Also, given the criteria, it may be better to find a list of all the members that DON'T satisfy the conditions, then check for all members not in that set.

Code:
SELECT   *
  FROM   members
 WHERE   member_id NOT IN
               (SELECT   m.member_id
                  FROM      members m
                         JOIN
                            (SELECT   sm.member_id,
                                      s.session_id,
                                      s.session_date
                               FROM      sessions s
                                      JOIN
                                         member_sessions ms
                                      ON s.session_id = ms.session_id
                                         AND s.session_id = @session_id) ms
                         ON m.member_id = ms.member_id
                            OR (m.membership_start >= ms.session_date
                                OR m.membership_end <= ms.session_date));


Would love for someone to tear apart my code though. I'm sure there's a better way to do this.
 

ettevoj

Smack-Fu Master, in training
73
Try this T-SQL query (sorry I am not familiar with PLSQL but there's no TSQL specific syntax with the following that I know of)

Code:
select a.ID as MEMBER_ID
from MEMBERS a
left join SESSIONS b on b.ID=@SESSION_ID
where a.ID not in 
(
	select MEMBER_ID from MEMBERS_SESSIONS where SESSION_ID=@SESSION_ID
)
and 
a.DATE_BEGIN <= b.DATE_SESSION
and
a.DATE_END >= b.DATE_SESSION

I tested this using T-SQL, here's the complete sample

Code:
declare @MEMBERS table (ID int, FIRST_NAME varchar(50), LAST_NAME varchar(50), DATE_BEGIN datetime, DATE_END datetime)

insert into @MEMBERS (ID, FIRST_NAME, LAST_NAME, DATE_BEGIN, DATE_END)
values (5, 'Joe', 'Smith', GETDATE(), DATEADD(DAY, 10, GETDATE())) -- Attended
insert into @MEMBERS (ID, FIRST_NAME, LAST_NAME, DATE_BEGIN, DATE_END)
values (6, 'John', 'Doe', GETDATE(), DATEADD(DAY, 10, GETDATE())) 
insert into @MEMBERS (ID, FIRST_NAME, LAST_NAME, DATE_BEGIN, DATE_END)
values (7, 'Jane', 'Smith', GETDATE(), DATEADD(DAY, 5, GETDATE())) -- Date End 
insert into @MEMBERS (ID, FIRST_NAME, LAST_NAME, DATE_BEGIN, DATE_END)
values (8, 'Jane', 'Doe', DATEADD(DAY, 10, GETDATE()), DATEADD(DAY, 20, GETDATE()))
--select * from @MEMBERS

declare @SESSIONS table (ID int, DATE_SESSION datetime)

insert into @SESSIONS (ID, DATE_SESSION)
values (10, DATEADD(DAY, 9, GETDATE()))

--select * from @SESSIONS

declare @MEMBERS_SESSIONS table (MEMBER_ID int, SESSION_ID int)


insert into @MEMBERS_SESSIONS (MEMBER_ID, SESSION_ID)
values (5,10)


--select * from @MEMBERS_SESSIONS

declare @SESSION_ID int
set @SESSION_ID = 10

select a.ID as MEMBER_ID
from @MEMBERS a
left join @SESSIONS b on b.ID=@SESSION_ID
where a.ID not in 
(
	select MEMBER_ID from @MEMBERS_SESSIONS where SESSION_ID=@SESSION_ID
)
and 
a.DATE_BEGIN <= b.DATE_SESSION
and
a.DATE_END >= b.DATE_SESSION
 

Mister E. Meat

Ars Tribunus Angusticlavius
7,571
Subscriptor
ettevoj":1mfwbi2f said:
Try this T-SQL query (sorry I am not familiar with PLSQL but there's no TSQL specific syntax with the following that I know of)

Code:
select a.ID as MEMBER_ID
from MEMBERS a
left join SESSIONS b on b.ID=@SESSION_ID
where a.ID not in 
(
	select MEMBER_ID from MEMBERS_SESSIONS where SESSION_ID=@SESSION_ID
)
and 
a.DATE_BEGIN <= b.DATE_SESSION
and
a.DATE_END >= b.DATE_SESSION
Don't use in. If anything, use exists like was posted above so that it will short circuit. This also won't take care of the fact where he wants only the members that are not already part of the session.

I would write it like this in T-SQL, but I'm not sure if you can use derived tables in Oracle.
Code:
SELECT m.MEMBER_ID FROM
MEMBER m LEFT JOIN 
(Select ms.MEMBER_ID from MEMBERS_SESSIONS as ms join SESSIONS as s on ms.SESSION_ID = s.SESSION_ID
WHERE s.DATE between @START and @END
and s.SESSION_ID = @SESSIONID
) as sess on m.MEMBER_ID = sess.MEMBER_ID
WHERE sess.MEMBER_ID IS NULL
 

ettevoj

Smack-Fu Master, in training
73
Mister E. Meat":2cm6zvc4 said:
Don't use in. If anything, use exists like was posted above so that it will short circuit. This also won't take care of the fact where he wants only the members that are not already part of the session.

Please state your justification but thanks for pointing it out. I googled it and found the subtle difference and performance penalty. The 'not in' can be rewritten as:

Code:
select a.ID as MEMBER_ID
from @MEMBERS a
left join @SESSIONS b on b.ID=@SESSION_ID
left join @MEMBERS_SESSIONS c on c.SESSION_ID=@SESSION_ID and c.MEMBER_ID=a.ID
where c.SESSION_ID is null
and 
a.DATE_BEGIN <= b.DATE_SESSION
and
a.DATE_END >= b.DATE_SESSION
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
Sure, but that's way less clear. The first Left Join looks like a Cartesian product unless you read the filter clause out of order (hope the productionized query fits on one screen!). May even be implemented as one, if your RDBMS is as dumb as mine.

SQL without subqueries is like algebra without parentheses. (Quite literally, if you understand the algebraic structure of what you're writing). Strictly less expressive; frequently harder to write; virtually impossible to transform into modular, testable, reusable code. Whoever introduced the popular superstition that Joins were better should be sentenced to, I dunno, VB6 maintenance.

(this is not a rebuttal of the side argument about Exists vs In, which has both mathematical and implementation consequences)
 
Status
Not open for further replies.