常用SQL

  • 单表根据某字段去重,保留主键ID最小一条。需要移除SQL_MODEL中的ONLY_FULL_GROUP_BY。通过SELECT @@SQL_MODE;命令查看。
常用SQL
-- 移除wm_im_notice_i表中other_id重复的并且保留ID最小的行。
DELETE
FROM
    `wm_im_notice_i`
WHERE
    `other_id` IN(
    SELECT
        other_id
    FROM
        (
        SELECT
            `other_id`
        FROM
            `wm_im_notice_i`
        GROUP BY
            `other_id`
        HAVING
            COUNT(*) > 1
    ) AS t1
) AND id NOT IN(
    SELECT
        id
    FROM
        (
        SELECT
            MIN(id) AS id
        FROM
            `wm_im_notice_i`
        GROUP BY
            `other_id`
        HAVING
            COUNT(*) > 1
    ) AS t2
)
View Code
  •  连表更新
常用SQL
-- eg 左连接
UPDATE wm_im_notice_i AS i
        LEFT JOIN
    wm_im_notice_h AS h ON h.im_cus_code = i.im_cus_code 
SET 
    i.im_notice_id = h.notice_id
View Code

 

常用SQL

上一篇:centos 安装MySQL全过程


下一篇:一个坑:java.sql.ResultSet.getInt==》the column value; if the value is SQL NULL, the value returned is 0