2012-01-25 71 views
1

我有两张桌子,我们称他们为会议和打电话。他们都实现了一个“事件”界面,因此它们之间有共同的字段,如日期,主题,参与者等等。SQL:可以根据2列中的1列对结果集进行排序吗?

我想运行一个查询来抓取一个结果集中的会议和电话,并按日期排序。这可能吗?

Thx for reading!

+0

你想从这些表中选择哪些列?你想显示一个事件的结果吗? – Lamak

回答

2

你可以这样做:

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

或者,你可以在两个类映射到三个表:

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) 
) 

这样,所有常用数据将在同一个表中结束。阅读会更复杂一些,因为您需要加入到事件表中以获取公共字段。无论如何,每种选择都有其优缺点,选择取决于你。

2

是:

select commonFields 
from events 
join meetings 

union all 

select commonFields 
from events 
join calls 

order by date 

这是伪代码,但你可以把它的工作。

2

是的。

表:

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 

类型列必须是同一寿。 希望有所帮助。

编辑:添加了“类型”(会议/活动),所以你知道什么表来搜索更多的信息。

2

像下面这样的东西应该会看到你的(注意这是基于TSQL的,但对于mysql应该是相似/相同的)。您可以包含每个表中的不同列,并将NULL作为另一个表的列值,反之亦然。

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 
相关问题