两张表相同字段同列输出(union/unionAll)

本文介绍了一种从两个不同的数据库表中联合查询特定字段的方法,并通过时间限制和分页功能展示结果。主要关注如何使用SQL语句实现跨表查询,同时确保数据按时间排序并限定在最近三个月内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

事先阅读

http://www.w3school.com.cn/sql/sql_union.asp

表1:

CREATE TABLE `A` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `orderno` bigint(20) DEFAULT NULL ,
  `userid` varchar(255) DEFAULT NULL,
  `resultid` tinyint(11) DEFAULT NULL,
  `remark` varchar(255) DEFAULT NULL,
  `createtime` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `role` int(1) DEFAULT NULL ,
  `nickname` varchar(20) DEFAULT NULL,
  `headimgurl` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=756 DEFAULT CHARSET=utf8;

表2:

CREATE TABLE `B` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `orderno` bigint(20) NOT NULL ,
  `payamount` decimal(12,2) DEFAULT NULL,
  `createdat` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ,
  `checkuserid` varchar(32) NOT NULL ,
  `picurls` text ,
  `status` tinyint(2) NOT NULL ,
  `productid` varchar(32) DEFAULT NULL,
  `checktype` tinyint(2) NOT NULL,
  `detail` varchar(255) DEFAULT NULL,
  `newuserid` int(11) NOT NULL,
  `nickname` varchar(200) DEFAULT NULL,
  `mobile` varchar(32) DEFAULT NULL ,
  `productname` varchar(255) DEFAULT NULL,
  `remark` varchar(255) DEFAULT NULL ,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;

需求:

1.获取两张表的orderno

2.按时间排序

2.区分是从哪张表中获取的orderno

3.时间限定在3个月内,

4.进行分页。

sql

        SELECT orderno,resource from 
        (select DISTINCT orderno,createtime as time,1 as resource
        from A where userid =666
        UNION
        SELECT orderno,createdat as time,0 as resource
        from B where checkuserid = 666)
        as a where time>=DATE_SUB(SYSDATE(),INTERVAL 3 MONTH) ORDER BY time DESC LIMIT 0,20

解释

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值