简体   繁体   中英

SQL: can a result set be sorted based on 1 of 2 columns?

I have two tables, let's call them meetings and phone calls. They both implement an "event" interface, and therefore have common fields between them such as date, subject, participants, etc etc.

I would like to run a query to grab both meetings and phone calls in one result set, and sort them by date. Is this possible?

Thx for reading!

Yes:

select commonFields
from events
join meetings

union all

select commonFields
from events
join calls

order by date

This is pseudo code but you can make it work.

You can do this:

(select time, subject from meetings
union all
select time, subject from phonecalls)
)
order by time

Alternatively, you can map two classes to three tables:

create table events ( -- common columns go here
    event_id bigint
,   event_time datetime
,   event_subject varchar(max)
)

create table phone_calls (
    event_id bigint
,   phone_number varchar(24)
)

create table meetings (
    event_id bigint
,   location varchar(max)
)

This way, all common data will end up in the same table. Reading would be a bit more complex, because you would need to join to the event table to get the common fields. Anyway, there are pluses and minuses to each alternative, the choice is up to you.

Something like the following should see you right (note this is based on TSQL but should be similar/same for mysql). You can include different columns from each table and provide NULL as the column value for the other table and vice versa.

SELECT EventDate
    , EventSubject
    , Particpants
    , DifferentMeetingsColumn
    , NULL AS DifferentPhoneCallsColumn
FROM Meetings
UNION ALL
SELECT EventDate
    , EventSubject
    , Participants
    , NULL AS DifferentMeetingsColumn
    , DifferentPhoneCallsColumn
FROM PhoneCalls
ORDER BY EventDate

Yes.

Tables:

Meeting: m_id, m_date, m_subject
Event: e_id, e_date, e_subject


( SELECT m_id,m_date,m_subject,'meeting' FROM meeting
  UNION ALL
  SELECT eid,e_date,e_subject,'event' FROM event ) ORDER BY 2

The types of the columns have to be the same tho. Hope that helps.

Edit: Added the "type" (meeting/event) so you know what table to search for further information.

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