简体   繁体   中英

Compare 1 row of returned data from multi-row nested SQL statement

I have two tables... EVENT (Primary key is EID) (containing all the general event data) and SINGLE_EVENT (Primary Key is SEID) (containing the information about each individual event related to a particular event ID ie date and time of the individual event, location of the venue etc.

In summary I want to find the 'single event' which is happening soonest for each overall event(EID) -- this should return a single event for each unique EID in the SINGLE_EVENTS table I then want to bind the overall EVENT information to the returned results.

The problem is that, with the current MySQL statement I have below, I need to select * for the nested query to have all the information it needs to process the query but I also DONT want to select all that information because I only need the SEID from that query result (and not the whole table)

here is my query (obviously executed without the comments):

<!-- non working outer query...
SELECT SINGLE_EVENT.SEID, EVENT.* FROM EVENT 
INNER JOIN SINGLE_EVENT ON SINGLE_EVENT.EID=EVENT.EID 
WHERE SINGLE_EVENT.SEID IN ( 
-->
<!-- working sub query...
select * from SINGLE_EVENT t
inner join (select eid, min(date) as MinDate from SINGLE_EVENT 
            group by eid) tm 
on t.eid=tm.eid and t.date=tm.MinDate and t.date>=sysdate()
-->
)

I am new to SQL and dont know how best to find this information out from the tables. I feel that I'm very close to it working but I keep getting the message "Operand should contain 1 column(s)" because of the multi-column return value of the sub-query.

Any help is appreciated.

In your subquery, change:

select * from SINGLE_EVENT t

to

select SEID from SINGLE_EVENT t

You're effectively telling it to search the whole table for the SEID, which isn't allowed in a subquery.

If you specify which column the subquery is looking for matches, that should solve your problem.

You can simply join first with your aggregates and then with your real table:

select e.*, se.*
from event e
join 
(
  select eid, min(date) as date 
  from single_event
  where date >= sysdate()
  group by eid
) first_events on first_events.eid = e.eid
join single_event se on se.eid = first_events.eid and se.date = first_events.date;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM