(SQL学习随笔4)SQL语法——UPDATE与DELETE

-- 创建上海部分房源信息表
-- PostgreSQL
CREATE TABLE houses
(
    area      VARCHAR,
    community VARCHAR,
    room      INT,
    hall      INT,
    dimension FLOAT,
    towards   VARCHAR,
    furnish   VARCHAR,
    floor     VARCHAR,
    year      INT,
    elevator  VARCHAR,
    t_price   FLOAT,
    u_price   FLOAT
);
-- MySQL
-- 创建上海部分房源信息表
CREATE TABLE houses
(
    area      TEXT,
    community TEXT,
    room      INT,
    hall      INT,
    dimension FLOAT,
    towards   TEXT,
    furnish   TEXT,
    floor     TEXT,
    year      INT,
    elevator  TEXT,
    t_price   FLOAT,
    u_price   FLOAT
);


INSERT INTO houses
VALUES ('闵行', '黎安四村', 2, 1, 65.85, '南 北', '精装', '高楼层 (共6层)', 1997, '无', 368.0, 55885),
       ('浦东', '云帆花苑', 2, 1, 82.3, '南 北', '简装', '低楼层 (共12层)', 2008, '无', 185.0, 22479),
       ('静安', '昌林公寓', 2, 1, 68.32, '南', '简装', '低楼层 (共6层)', 1996, '无', 390.0, 57085),
       ('杨浦', '星云苑', 3, 2, 129.04, '南 北', '精装', '低楼层 (共14层)', 2007, '有', 980.0, 75946),
       ('长宁', '安顺路231弄', 2, 1, 50.69, '南', '精装', '高楼层 (共6层)', 1979, '无', 385.0, 75952),
       ('杨浦', '鞍山四村第三小区', 1, 0, 26.61, '西南 西北', '精装', '中楼层 (共5层)', 1969, '无', 212.0, 79670),

UPDATE

UPDATE houses
SET area = '徐汇区'
WHERE area = '徐汇';
  • 结合CASE-WHEN-THEN-EN语句
UPDATE houses
SET area =
        CASE
            WHEN area = '徐汇'
                THEN '徐汇区'
            WHEN area = '宝山'
                THEN '宝山区'
            WHEN area = '嘉定'
                THEN '嘉定区'
            ELSE area
            END;
  • 结合运算符
-- 单价转换为万
UPDATE houses
SET u_price = u_price / 10000;

DELETE

DELETE
FROM houses
WHERE area = '徐汇区';

SELECT COUNT(1) FROM houses WHERE area = '徐汇区'; -- 返回0

DELETE操作直接删除行,如果只想要删除某行中的某些字段,可以使用UPDATE将对应字段更新为NULL

你可能感兴趣的:(SQL,sql,数据库)