• MySQL多个相同结构的表查询并把结果合并放在一起的语句(union all)


    union all

    select *,'1' as category from table1001 where price > 10
    union all
    select *,'2' as category from table1002 where price > 10
    union all
    select *,'3' as category from table1003 where price > 10
    order by ID

    列的个数要保持一致,列名可以不一样,但是对应的列的数据类型要一样。同样可以使用order by,limit这些。

    例如对于大数据的横向分表后,可以使用此方法查询。

    如果其中某个表新增了字段,可以改为查询固定的字段进行 union all.例如:

    select id,name,age from table1001 where price > 10
    union all
    select id,name,age from table1002 where price > 10
    union all
    select id,name,age from table1003 where price > 10
    order by ID

    参考:

    http://bbs.51cto.com/thread-1076108-1-1.html


    MySQL使用select查询时,在查询结果中增加一个字段并指定固定值

     

    假设需求是这样的:

    1
    2
    3
    4
    5
    6
    7
    8
    mysql> desc user;
    +-------+----------+------+-----+---------+----------------+
    | Field | Type     | Null | Key | Default | Extra          |
    +-------+----------+------+-----+---------+----------------+
    | id    | int(11)  | NO   | PRI | NULL    | auto_increment |
    | name  | char(30) | NO   |     | NULL    |                |
    +-------+----------+------+-----+---------+----------------+
    2 rows in set (0.01 sec)

      假设user表中,有id和name两个字段,现在需要查询user表中所有数据,并增加一个字段(is_person),判断该记录所描述的是不是一个人? 

      别去钻牛角尖,很明显,is_person的值始终为true,那么在查询的时候,就可以在返回结果中新增一个字段is_person,并指定值为true。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    mysql> select * from user;
    +----+------+
    | id | name |
    +----+------+
    |  1 | abc  |
    |  2 | xyz  |
    +----+------+
    2 rows in set (0.00 sec)
     
    mysql> select *,"true" as is_person from user;
    +----+------+-----------+
    | id | name | is_person |
    +----+------+-----------+
    |  1 | abc  | true      |
    |  2 | xyz  | true      |
    +----+------+-----------+
    2 rows in set (0.00 sec)

    注意上面的格式,使用关键字as,这里的as和平时使用的as代表的意思是相同的!!!

      平常使用as是为字段取一个别名,as的左边是一个原始字段名,右边是新的别名,该别名会显示在查询结果中,而原始字段名代表的就是该字段的值;

      此处为新增字段指定固定值,as的左边为新增字段的固定值,右边才是新增字段的字段名,此时字段名不用加引号,如果固定值为数值型则不用加引号,如果固定值为其他类型则必须加引号。

  • 相关阅读:
    springmvc 注解式开发 处理器方法的返回值
    springmvc 注解式开发 接收请求参数
    【洛谷P1379】八数码难题 状压bfs
    【模板】ST表
    【POJ1741】Tree
    【洛谷P1073】最优贸易
    【POJ3662】Telephone Lines dij + 二分答案
    【模板】spfa
    【洛谷P2384】最短乘积路径
    【bzoj2038】小Z的袜子
  • 原文地址:https://www.cnblogs.com/rxbook/p/9282602.html
Copyright © 2020-2023  润新知