SQL语句中UNION的用法

实例:
数据库中有2张表,2张表中都有我需要的记录,
要将2张表中的记录一起取出来进行排序,这需要用UNION把2张表合并在一起。

表①:t_event

iduser_idtitlecommenttimedisplay
1478hihow are u?2007-06-161

表②:t_topics

iduser_idtitlecommenttimedisplay
1478himy name is zj2007-06-180
2478hinice to meet u2007-06-201

SQL语句:
SELECT * FROM (
    SELECT
        'event' as flag,
        t_event.id as id,
        t_event.user_id as user_id,
        t_event.title as title,
        t_event.comment as comment,
        t_event.time as time,
        t_event.display as display
    FROM
        t_event
    UNION
    SELECT
        'topics' as flag,
        t_topics.id as id,
        t_topics.user_id as user_id,
        t_topics.title as title,
        t_topics.comment as comment,
        t_topics.time as time,
        t_topics.display as display
    FROM
        t_topics
) as union
WHERE
    user_id = 478 and
    display  =  true
ORDER BY 
    time DESC
OFFSET ?
LIMIT ?

结果:

flagiduser_idtitlecommenttimedisplay
topics2478hinice to meet u2007-06-201
event1478hihow are u?2007-06-161

这样就把2张表里满足user_id=478并且display=1的记录取出来放在一起,按时间降序进行排序。
需要注意的是,2张表对应的字段类型必须相同,如果不同,可以强制转换。比如用Bool()把int转成bool型,用Date()把vchar转成timestamp型。

疑问:
UNION和UNION ALL有什么区别还是不知道,如果有高手路过,还望指点一二。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值