常用 SQL 语句

134 阅读1分钟

查询语句

查询全部
select * from database;

按时间查询
select time , name from database  where  time > '2020-12-01';

多条件查询
select time , name from database  where  time > '2020-12-01' and name = 'xx';

select * from database  where  time  between "2023-05-05" and "2023-06-24" and (name="xx")

模糊查询
SELECT * FROM database WHERE name LIKE CONCAT('%', 'x', '%');

查询最新时间一条的数据
select time from database where time = (select max(time) from database) LIMIT 1;

查询小于当前时间的n条数据
SELECT * FROM database WHERE time  < '2021-12-01' ORDER BY time DESC LIMIT 30;

查询当天起最近n天的数据
SELECT * FROM `database` WHERE time  > DATE_SUB(NOW(), INTERVAL 10 DAY);

删除语句

单个删除
delete  from database where id = #{id};

多个删除
delete from database where id in (0, 1, 2);

新增语句

新增单条数据
insert INTO database VALUES (字段1,字段2);

新增多条
INSERT INTO database (字段1,字段2) VALUES(值1,值2),(值1,值2),(值1,值2);

给指定值添加数据 
INSERT INTO database (字段2) VALUES (值2);

更新语句

UPDATE database SET name = #{name} WHERE id = #{id}

数据库表字段和 Java 关键字 冲突了怎么解决


使用映射
    自定义映射规则: resultMap标签来完成映射规则的定义 
        <resultMap id="" type="entity"></resultMap>
    属性:
        column属性:表示表中的字段名称
        property属性:属性表示类中的属性名称

使用
    将表的资源和类的属性不一致的字段进行匹配指定 名称一致的字段可以省略不写
    在定义映射规则时主键是不可以省略的 


    <resultMap id="classMap" type="entity">
        <id column="id" property="id"></id>
        <result column="Class" property="cls"></result>
    </resultMap>


    <select id="xx" resultMap="classMap">
        select * from database
    </select>