SQL SELECT query not working - sql

SELECT s1.id,
s3.food_name,
Count(*) AS TotalRefill
FROM (SELECT ( s1.food_value - s2.food_value ) AS difference
FROM `serving_info` s1,
`serving_info` s2
WHERE s1.id - s2.id = '1'
AND s1.food_name = 'Shrimp'
AND s2.food_name = 'Shrimp') AS diff,
`serving_info` s3
WHERE s3.id = diff.id
AND s3.food_value >= '990'
AND diff.difference >= '150'
Result: #1054 - Unknown column 's1.id' in 'field list'
--
-- Table structure for table `employees`
--
CREATE TABLE IF NOT EXISTS `employees` (
`id_user` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`email` varchar(64) NOT NULL,
`phone_number` varchar(16) NOT NULL,
`username` varchar(16) NOT NULL,
`password` varchar(32) NOT NULL,
`confirmcode` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id_user`),
KEY (name)
);
--
-- Table structure for table `Foods`
--
CREATE TABLE IF NOT EXISTS `Foods` (
`Food_name` varchar(40) NOT NULL,
`CostPerRefill` double NOT NULL,
PRIMARY KEY (`Food_name`)
);
--
-- Table structure for table `Serving_Info`
--
CREATE TABLE IF NOT EXISTS `Serving_Info` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`Food_Value` varchar(40) NOT NULL,
`Food_name` varchar(40) NOT NULL,
`Served_On` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`Oncall` varchar(128),
Foreign key(`Oncall`) REFERENCES `employees`(`name`),
Foreign key(`Food_name`) REFERENCES `Foods`(`Food_name`),
PRIMARY KEY (`id`),
UNIQUE (`Oncall`,`Food_name`, `Served_On`)
);
What is causing the s1 to not be declared? For some reason the s1 instance isn't detected by the s1.id. I have been trying to figure out from a while by changing different brackets but I really cannot figure out how to debug this..I have tried changing the position of the close bracket but that would mess up the query.

What all others here said is right, but just to give you a more preceise solution, look at the query below it should not be s1.id but it should be diff.id
SELECT diff.id,
s3.food_name,
Count(*) AS TotalRefill
FROM (SELECT ( s1.food_value - s2.food_value ) AS difference, s1.id
FROM `serving_info` s1,
`serving_info` s2
WHERE s1.id - s2.id = '1'
AND s1.food_name = 'Shrimp'
AND s2.food_name = 'Shrimp') AS diff,
`serving_info` s3
WHERE s3.id = diff.id
AND s3.food_value >= '990'
AND diff.difference >= '150'

S1is defined inside the parentheses and thus not visible outside them, where you reference it.

Because s1 is only defined in the inner select so not is scope. Select either diff.id or s3.id (they will be the same value as you are joining on it).

The table s1 is not in the from part of your query in which you are trying to select it, it's only in a subquery.

Related

How to combine two selects with same value but not the same INNER JOIN

I have to need a project school, a site like ebay
with bid.
I have to make a select who select
the name of the seller
the name of the last "customer" (bid)
BUT THE PROBLEM is that there two value was in the same table, so for access to the value I need to make 2 select with different INNER JOIN (look the diag for understand)
I have made two selects but I don't understand how to make a single select.
SELECT nom AS nameSeller
FROM ENCHERES e
INNER JOIN ARTICLES_VENDUS ac ON ac.no_article = e.no_article
INNER JOIN UTILISATEURS u ON u.no_utilisateur = ac.no_utilisateur
WHERE nom_article LIKE '%ta%'
SELECT nom AS nameCustomer
FROM ENCHERES e
INNER JOIN UTILISATEURS u ON e.no_utilisateur = u.no_utilisateur
WHERE e.no_utilisateur= 57
what i have with two select
First select
nameCustomer
john
Second select
nameSeller
bryan
What i want in one select
nameSeller
nameCustomer
bryan
john
Fil to the script to create table and bdd
-- Script de création de la base de données ENCHERES
-- type : SQL Server 2012
--
CREATE DATABASE BDDTEST2
GO
USE BDDTEST2
GO
CREATE TABLE CATEGORIES (
no_categorie INTEGER IDENTITY(1,1) NOT NULL,
libelle VARCHAR(30) NOT NULL
)
ALTER TABLE CATEGORIES ADD constraint categorie_pk PRIMARY KEY (no_categorie)
CREATE TABLE ENCHERES (
no_utilisateur INTEGER NOT NULL,
no_article INTEGER NOT NULL,
date_enchere datetime NOT NULL,
montant_enchere INTEGER NOT NULL
)
ALTER TABLE ENCHERES ADD constraint enchere_pk PRIMARY KEY (no_utilisateur, no_article)
CREATE TABLE RETRAITS (
no_article INTEGER NOT NULL,
rue VARCHAR(30) NOT NULL,
code_postal VARCHAR(15) NOT NULL,
ville VARCHAR(30) NOT NULL
)
ALTER TABLE RETRAITS ADD constraint retrait_pk PRIMARY KEY (no_article)
CREATE TABLE UTILISATEURS (
no_utilisateur INTEGER IDENTITY(1,1) NOT NULL,
pseudo VARCHAR(30) NOT NULL,
nom VARCHAR(30) NOT NULL,
prenom VARCHAR(30) NOT NULL,
email VARCHAR(20) NOT NULL,
telephone VARCHAR(15),
rue VARCHAR(30) NOT NULL,
code_postal VARCHAR(10) NOT NULL,
ville VARCHAR(30) NOT NULL,
mot_de_passe VARCHAR(30) NOT NULL,
credit INTEGER NOT NULL,
administrateur bit NOT NULL
)
ALTER TABLE UTILISATEURS ADD constraint utilisateur_pk PRIMARY KEY (no_utilisateur)
CREATE TABLE ARTICLES_VENDUS (
no_article INTEGER IDENTITY(1,1) NOT NULL,
nom_article VARCHAR(30) NOT NULL,
description VARCHAR(300) NOT NULL,
date_debut_encheres DATE NOT NULL,
date_fin_encheres DATE NOT NULL,
prix_initial INTEGER,
prix_vente INTEGER,
no_utilisateur INTEGER NOT NULL,
no_categorie INTEGER NOT NULL
)
ALTER TABLE ARTICLES_VENDUS ADD constraint articles_vendus_pk PRIMARY KEY (no_article)
ALTER TABLE ARTICLES_VENDUS
ADD CONSTRAINT encheres_utilisateur_fk FOREIGN KEY ( no_utilisateur )
REFERENCES UTILISATEURS ( no_utilisateur )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE ENCHERES
ADD CONSTRAINT encheres_articles_vendus_fk FOREIGN KEY ( no_article )
REFERENCES ARTICLES_VENDUS ( no_article )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE RETRAITS
ADD CONSTRAINT retraits_articles_vendus_fk FOREIGN KEY ( no_article )
REFERENCES ARTICLES_VENDUS ( no_article )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE ARTICLES_VENDUS
ADD CONSTRAINT articles_vendus_categories_fk FOREIGN KEY ( no_categorie )
REFERENCES CATEGORIES ( no_categorie )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE ARTICLES_VENDUS
ADD CONSTRAINT ventes_utilisateur_fk FOREIGN KEY ( no_utilisateur )
REFERENCES UTILISATEURS ( no_utilisateur )
ON DELETE NO ACTION
ON UPDATE no action
Link to insert value
USE BDDTEST2
GO
INSERT INTO [dbo].[UTILISATEURS]
([pseudo]
,[nom]
,[prenom]
,[email]
,[telephone]
,[rue]
,[code_postal]
,[ville]
,[mot_de_passe]
,[credit]
,[administrateur])
VALUES
('zorg'
,'john'
,'john'
,'j#k.c'
,'15454'
,'hjh'
,'hkk'
,'hjgjh'
,'hjkjg'
,0
,0 )
GO
INSERT INTO [dbo].[UTILISATEURS]
([pseudo]
,[nom]
,[prenom]
,[email]
,[telephone]
,[rue]
,[code_postal]
,[ville]
,[mot_de_passe]
,[credit]
,[administrateur])
VALUES
('zorg'
,'bryan'
,'bryan'
,'j#k.c'
,'15454'
,'hjh'
,'hkk'
,'hjgjh'
,'hjkjg'
,0
,0 )
GO
INSERT INTO [dbo].[CATEGORIES]
([libelle])
VALUES
('enfant')
GO
INSERT INTO [dbo].[ARTICLES_VENDUS]
([nom_article]
,[description]
,[date_debut_encheres]
,[date_fin_encheres]
,[prix_initial]
,[prix_vente]
,[no_utilisateur]
,[no_categorie])
VALUES
('Jouet',
'desc',
'2002-01-01',
'2003-01-01',
0,
0,
2,
1)
GO
INSERT INTO [dbo].[ENCHERES]
([no_utilisateur]
,[no_article]
,[date_enchere]
,[montant_enchere])
VALUES
(1,
1,
'2002-02-02',
50)
GO
Thanks
You can use a CROSS APPLY to pull back the buyer for each of the sellers. Consider the following:
SELECT u.nom AS nameSeller, x.nom nameBuyer
FROM ENCHERES e
INNER JOIN ARTICLES_VENDUS ac ON ac.no_article = e.no_article
INNER JOIN UTILISATEURS u ON u.no_utilisateur = ac.no_utilisateur
CROSS APPLY(
select u.nom
from UTILISATEURS u WHERE u.no_utilisateur = e.no_utilisateur
) X
lead will move the current row to 1 place above
Union will join data in single column
you need to have a common factor like date for order by clause
https://www.mssqltips.com/sqlservertutorial/9127/sql-server-window-functions-lead-and-lag/
with main_data as (
SELECT nom AS nameSeller,
'Seller' as category_seller_or_customer
FROM ENCHERES e
INNER JOIN ARTICLES_VENDUS ac ON ac.no_article = e.no_article
INNER JOIN UTILISATEURS u ON u.no_utilisateur = ac.no_utilisateur
WHERE nom_article LIKE '%ta%'
union
SELECT nom AS nameCustomer,
'Customer' as category_seller_or_customer
FROM ENCHERES e
INNER JOIN UTILISATEURS u ON e.no_utilisateur = u.no_utilisateur
WHERE e.no_utilisateur= 57
),
getting_seller_and_buyer AS (
select
*,
lead(category_seller_or_customer)
over(order by
[some date factor or something that both have in common]
) as current_seller_or_customer
from main_data
)
select
*,
case
when category = 'Seller' then current_seller_or_customer else end as seller,
case
when category = 'Customer' then current_seller_or_customer else end as customer
from
getting_seller_and_buyer

SQL How to convert this to a SubQuery?

Learning, be kind.
I am trying to understand how this works and I have done several successful conversions, but this one I am stumped on.
How do I take this code and convert it to a subquery? I'm a little lost.
SELECT o.FirstName + ' ' + o.LastName AS Driver, COUNT(DISTINCT s.vehicleID) NoOfBusesUsed
FROM Operators AS o, Runs AS r, Schedules AS s JOIN Trips AS t
ON s.scheduleID = t.scheduleID
WHERE r.BidDate BETWEEN '09/01/2004' AND '09/30/2004'
GROUP BY o.FirstName + ' ' + o.LastName
HAVING COUNT(s.vehicleID) > 1
Here is how my tables are setup. If more info is needed, I can post.
CREATE TABLE Operators
(
SeniorityNumber char(4) NOT NULL
CONSTRAINT ck_Operators_Seniority
CHECK (SeniorityNumber LIKE '[0-9][0-9][0-9][0-9]'),
FirstName varchar(25) NOT NULL,
LastName varchar(35) NOT NULL,
HireDate smalldatetime
CONSTRAINT ck_Operators_HireDate CHECK (HireDate <=Getdate())
)
CREATE TABLE Trips
(
RouteNumber varchar(4) NOT NULL,
StartLocation varchar(50) NOT NULL,
StartTime time NOT NULL,
EndLocation varchar(50) NOT NULL,
EndTime time NOT NULL,
EffectiveDate smalldatetime NOT NULL
CHECK (EffectiveDate >= cast('1/1/2000' as smalldatetime)),
CONSTRAINT ck_Trips_StartEnd CHECK (EndTime > StartTime)
)
CREATE TABLE Vehicles
(
Manufacturer varchar(50)
DEFAULT 'Gillig',
Model varchar(50),
ModelYear int
DEFAULT DatePart(yyyy,GetDate())
CHECK (ModelYear <= DatePart(yyyy,GetDate())),
PurchaseDate smalldatetime
)
GO
ALTER TABLE operators
ADD OperatorID int IDENTITY --Primary Key
GO
ALTER TABLE Operators
ADD CONSTRAINT pkOperators Primary key (OperatorID)
ALTER TABLE Vehicles
ADD VehicleID int IDENTITY Primary Key
ALTER TABLE Trips
ADD TripID int IDENTITY Primary key
GO
CREATE TABLE Runs
(
RunID int IDENTITY NOT NULL Primary Key,
OperatorID int NOT NULL REFERENCES Operators,
BidDate date NOT NULL
CONSTRAINT ckRunBidDate CHECK
(biddate <= dateadd(mm,6,getdate())) --getdate() + 180
)
GO
CREATE TABLE Schedules
(
ScheduleID int IDENTITY Primary Key,
RunID int NOT NULL,
VehicleID int NOT NULL,
CONSTRAINT fk_Schedules_Runs FOREIGN KEY (RunID)
REFERENCES Runs(RunID),
CONSTRAINT fk_Schedules_Vehicles FOREIGN KEY (VehicleID)
REFERENCES Vehicles
)
ALTER TABLE Trips
ADD ScheduleID int NULL REFERENCES Schedules
When you want to use a query as a sub-query you can use WITH statement or a derived table like:
With:
;WITH subQuery AS (
/* Your query here */
)
SELECT *
FROM subQuery
Derived table
SELECT *
FROM (
/* your query here */
) As subQuery
I think you should use a query like this:
SELECT
o.FirstName + ' ' + o.LastName AS Driver,
DT.cnt AS NoOfBusesUsed
FROM
Operators AS o
JOIN
(SELECT
r.OperatorID,
COUNT(DISTINCT s.VehicleID) AS cnt
FROM
Schedules s
JOIN
Runs r ON s.RunID = r.RunID
) AS DT
ON DT.OperatorID = o.OperatorID
WHERE
ISNULL(DT.cnt, 0) > 1

Restricting values in a table used in a FULL OUTER JOIN

This concerns Oracle SQL.
Considering the following 3 tables:
TRIP_SEGMENT:
CREATE TABLE TRIP_SEGMENT(
SEG_ID NUMBER(6) NOT NULL,
DIRECTION VARCHAR(8) NOT NULL,
DEPARTURE_LOCATION VARCHAR(50) NOT NULL,
DESTINATION VARCHAR(50) NOT NULL,
SEGMENT_PRICE NUMBER(5,2) NULL,
TRIP_ID NUMBER(6) NOT NULL,
CONSTRAINT chk_SEG_DIRECTION CHECK (DIRECTION IN ('Outbound','Inbound')),
CONSTRAINT pk_SEGMENT PRIMARY KEY (SEG_ID),
CONSTRAINT fk_TRIP_ID FOREIGN KEY (TRIP_ID) REFERENCES TRIP(TRIP_ID)
);
TRANSPORTATION:
CREATE TABLE TRANSPORTATION(
TRANSP_BOOK_ID NUMBER(6) NOT NULL,
TRANSP_PRICE NUMBER(5,2) NULL,
DEPARTURE_DATE DATE NULL,
ARRIVAL_DATE DATE NULL,
EXT_BOOK_ID NUMBER(6) NULL,
SEG_ID NUMBER(6) NOT NULL,
SERV_TYPE_ID NUMBER(3) NOT NULL,
PARTNER_ID NUMBER(3) NULL,
CONSTRAINT pk_TRANSP_BOOK_ID PRIMARY KEY (TRANSP_BOOK_ID),
CONSTRAINT fk_TRANSP_SEG_ID FOREIGN KEY (SEG_ID) REFERENCES TRIP_SEGMENT(SEG_ID),
CONSTRAINT fk_TRANSP_SERV_ID FOREIGN KEY (SERV_TYPE_ID) REFERENCES SERVICE_TYPE(SERV_TYPE_ID),
CONSTRAINT fk_TRANSP_PARTNER_ID FOREIGN KEY (PARTNER_ID) REFERENCES PARTNER(PARTNER_ID)
);
PARTNER:
CREATE TABLE PARTNER(
PARTNER_ID NUMBER(3) NOT NULL,
PARTNER_NAME VARCHAR(50) NOT NULL,
CONTACT_FNAME VARCHAR(20) NOT NULL,
CONTACT_LNAME VARCHAR(20) NOT NULL,
ADDRESS VARCHAR(100) NULL,
PHONE_NO NUMBER(20) NOT NULL,
EMAIL VARCHAR(50) NULL,
SERV_TYPE_ID NUMBER(3) NOT NULL,
CONSTRAINT pk_PARTNER_ID PRIMARY KEY (PARTNER_ID),
CONSTRAINT fk_PART_SERV_ID FOREIGN KEY (SERV_TYPE_ID) REFERENCES SERVICE_TYPE(SERV_TYPE_ID)
);
I wanted to create a FULL OUTER JOIN like this:
SELECT TS.SEG_ID, TS.DEPARTURE_LOCATION, TS.DESTINATION, P.PARTNER_NAME
FROM TRIP_SEGMENT TS
FULL OUTER JOIN TRANSPORTATION T
ON TS.SEG_ID = T.SEG_ID
FULL OUTER JOIN PARTNER P
ON T.PARTNER_ID = P.PARTNER_ID;
...but have it restricted to PARTNER.PARTNER_ID < 6. If I just add a WHERE clause at the end of the JOIN, this will restrict all the values to those where there is an association with PARTNER.PARTNER_ID < 6, therefore defeating the purpose of the FULL OUTER JOIN.
So far, I've come up with this solution:
First, create a table that only contains PARTNER.PARTNER_ID < 6 :
CREATE TABLE TRANSPORTATION_PARTNER AS SELECT * FROM PARTNER WHERE PARTNER_ID < 6;
Then, use that table in the FULL OUTER JOIN instead:
SELECT TS.SEG_ID, TS.DEPARTURE_LOCATION, TS.DESTINATION, TP.PARTNER_NAME
FROM TRIP_SEGMENT TS
FULL OUTER JOIN TRANSPORTATION T
ON TS.SEG_ID = T.SEG_ID
FULL OUTER JOIN TRANSPORTATION_PARTNER TP
ON T.PARTNER_ID = TP.PARTNER_ID;
This works fine and it demonstrates what I'm trying to achieve, however I was wondering if there is a way of doing in one single query AND using a subquery.
Thank you!
YES, just do something like :
SELECT TS.SEG_ID, TS.DEPARTURE_LOCATION, TS.DESTINATION, P.PARTNER_NAME
FROM TRIP_SEGMENT TS
FULL OUTER JOIN TRANSPORTATION T
ON TS.SEG_ID = T.SEG_ID
FULL OUTER JOIN (SELECT *
FROM PARTNER
WHERE PARTNER.PARTNER_ID < 6) P
ON T.PARTNER_ID = P.PARTNER_ID;
You are placing restrictions on the rows to be selected so you can use LEFT JOIN instead of the FULL OUTER JOIN. Try something like
SELECT TS.SEG_ID, TS.DEPARTURE_LOCATION, TS.DESTINATION, P.PARTNER_NAME
FROM TRIP_SEGMENT TS
FULL OUTER JOIN TRANSPORTATION T
ON TS.SEG_ID = T.SEG_ID
LEFT OUTER JOIN PARTNER P
ON T.PARTNER_ID = P.PARTNER_ID AND P.Partner_ID = 6;

Hotel Reservation System Sql Query?

I want to build a Hotel Reservation System. For this system; database is also used fro an other program... But i have problem: before the reservation i want to see which number of rooms type are available for my for my reservation..
My table create sql querys
CREATE TABLE oteldb.oda (
oda_id INT (11) NOT NULL auto_increment,
oda_tip_id INT (11) DEFAULT NULL,
oda_adi VARCHAR (20) DEFAULT NULL,
PRIMARY KEY (oda_id)
)
ENGINE = MyISAM
AUTO_INCREMENT = 1
CHARACTER SET utf8
COLLATE utf8_general_ci;
CREATE TABLE oteldb.tip (
tip_id INT (11) NOT NULL auto_increment,
tip_adi VARCHAR (20) DEFAULT NULL,
PRIMARY KEY (tip_id)
)
ENGINE = MyISAM
AUTO_INCREMENT = 1
CHARACTER SET utf8
COLLATE utf8_general_ci
ROW_FORMAT = FIXED;
CREATE TABLE oteldb.rezervasyon (
rezervasyon_id INT (11) NOT NULL auto_increment,
rezervasyon_gt DATE DEFAULT NULL,
rezervasyon_ct DATE DEFAULT NULL,
rezervasyon_oda_id INT (11) DEFAULT NULL,
PRIMARY KEY (rezervasyon_id)
)
ENGINE = MyISAM
AUTO_INCREMENT = 1
CHARACTER SET utf8
COLLATE utf8_general_ci;
i try this but not work
SELECT
*
FROM
oteldb.tip
WHERE
IN tip.tip_id
(SELECT
oteldb.oda.oda_tip_id
FROM
oteldb.oda
WHERE
IN oda.oda_id note
(SELECT
oteldb.rezervasyon.rezervasyon_oda_id
FROM
oteldb.rezervasyon
WHERE
"2012-01-03" BETWEEN AND rezervasyon_ct rezervasyon_gt
AND "2012-01-22" AND BETWEEN rezervasyon_gt rezervasyon_ct))
thanks now...
Assuming that available rooms are those that are not already reserved at any time during the query period, and that rezervasyon_gt and rezervasyon_ct are the reservation start and end dates respectively, try:
select t.tip_adi, count(oda.oda_tip_id)
from oteldb.tip t
left join (select oda_tip_id
from oteldb.oda o
where not exists
(select null
from oteldb.rezervasyon r
where r.rezervasyon_oda_id = o.oda_id and
r.rezervasyon_gt <= '2012-01-22' and
'2012-01-03' <= r.rezervasyon_ct)
) oda on oda.oda_tip_id = t.tip_id
group by t.tip_adi
select
RoomType.tip_adi,
sum( if( Rooms.oda_id = BookedRooms.rezervasyon_oda_id, 0, 1 ) as AvailableCount
from
oteldb.oda Rooms
LEFT JOIN ( select distinct
res.rezervasyon_oda_id
from
oteldb.rezervasyo res
where
res.rezervasyon_gt between '2012-01-22' and '2012-01-03'
OR res.rezervasyon_ct between '2012-01-22' and '2012-01-03'
) BookedRooms
on Rooms.oda_id = BookedRooms.rezervasyon_oda_id
JOIN oteldb.tip RoomType
on Rooms.oda_tip_id = RoomType.tip_id

SQL joins query not acting as wanted

I have the following tables:
CREATE TABLE `attendance_event_attendance` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`talk_id` varchar(200) NOT NULL,
`membersAttended_id` varchar(200) NOT NULL,
PRIMARY KEY (`id`),
KEY `attendance_event_attendance_9ace4e5a` (`talk_id`),
KEY `attendance_event_attendance_3c0dadb7` (`membersAttended_id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
CREATE TABLE `attendance_member` (
`name` varchar(200) NOT NULL,
`telephone_number` varchar(200) NOT NULL,
`email_address` varchar(200) NOT NULL,
`membership_type` varchar(1) NOT NULL,
`membership_number` varchar(200) NOT NULL,
PRIMARY KEY (`membership_number`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE `attendance_talk` (
`title` varchar(200) NOT NULL,
`speaker` varchar(200) NOT NULL,
`date_of_talk` date NOT NULL,
PRIMARY KEY (`title`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
I want to select all the members that have not attended the two latest talks. The query I have written looks like this:
SELECT m.name
from attendance_member as m
left outer join attendance_event_attendance as ea on (ea.membersAttended_id=m.membership_number)
join attendance_talk as t on (ea.talk_id = t.title)
where t.date_of_talk >= 2010-06-01
AND ea.membersAttended_id = null;
Is this correct? Or have I not understood joins correctly?
A somewhat horrible approach, I fear - but one that should work...
SELECT m.name
from attendance_member as m
left outer join (
SELECT ea.membersAttended_id
FROM attendance_event_attendance as ea
join attendance_talk as t on (ea.talk_id = t.title)
where t.date_of_talk >= 2010-06-01
GROUP BY ea.membersAttended_id
HAVING COUNT(*) = 2
) attendingmembers
ON attendingmembers.membersAttended_id = m.membership_number
WHERE attendingmembers.membersAttended_id IS NULL
Pretty much exactly like you would say it in English
Select Distinct m.name -- Select names
From attendance_member M -- of members
Where Not Exists -- who did not attend the last two talks
(Select * From attendance_event_attendance a
Join attendance_talk t
On a.talk_id = t.title
Where a.membersAttended_id = m.membership_number
And (Select Count(*) From attendance_talk
Where date_of_talk >= t. date_of_talk) <= 2)
NOTE: The subquery:
(Select * From attendance_event_attendance a
Join attendance_talk t
On a.talk_id = t.title
Where a.membersAttended_id = m.membership_number -- (correlated w/outer query)
And (Select Count(*) From attendance_talk
Where date_of_talk >= t. date_of_talk) <= 2)
returns the list of members who attended the talks which have 2 or fewer subsequent talks