1. 程式人生 > >python mysql中不能在同一個sql語句中,先select同一個表的某些值,然後再update這個表。

python mysql中不能在同一個sql語句中,先select同一個表的某些值,然後再update這個表。

例:
首先新建表,插入值:

DROP TABLE IF EXISTS table_score_one;

CREATE TABLE table_score_one (
    id INT (10) NOT NULL PRIMARY KEY auto_increment,
    student_no VARCHAR (10) NOT NULL,
    student_name VARCHAR (10) NOT NULL,
    class_no VARCHAR (10) NOT NULL,
    class_name VARCHAR (10) NOT NULL,
    score INT
(10) NOT NULL ) DEFAULT CHARSET='utf8';
INSERT INTO `table_score_one` VALUES ('1', '201601', '張三', '0001', '數學', '98'); INSERT INTO `table_score_one` VALUES ('2', '201601', '張三', '0002', '語文', '66'); INSERT INTO `table_score_one` VALUES ('3', '201602', '李四', '0001', '數學', '60'); INSERT INTO `table_score_one` VALUES
('4', '201602', '李四', '0003', '英語', '78');
INSERT INTO `table_score_one` VALUES ('5', '201603', '王五', '0001', '數學', '99'); INSERT INTO `table_score_one` VALUES ('6', '201603', '王五', '0002', '語文', '99'); INSERT INTO `table_score_one` VALUES ('7', '201603', '王五', '0003', '英語', '98');

其中auto_increment表示按順序生成值。預設從1開始。
表如圖:
表:table_score_one


第二步更新值:

update table_score_one set class_name ='數學' , class_no = '0001' where id = 6;

如圖:
更新後
第三步:
把除了id不一樣的其餘都一樣的資料刪除。

delete table_test_one where id not in (select min(id) from table_test_one group by student_no, student_name, class_no, class_name, score);

上面的語句意思是:先通過根據student_no, student_name, class_no, class_name, score一樣的進行分組,查出每組最小的id,這樣再把不在查詢出的id結果中id刪除。
但是這樣會有一個錯誤:

You can’t specify target table ‘table_score_one’ for update in FROM clause
意思是:你不能在同一個sql語句中先查詢某些值,在修改這個表。
解決辦法:select的結果再通過一箇中間表select多一次。

DELETE
FROM
    table_score_one
WHERE
    id NOT IN (
        SELECT
            a.min_id
        FROM
            (
                SELECT
                    min(id) AS min_id
                FROM
                    table_score_one
                GROUP BY
                    student_no,
                    class_no,
                    class_name,
                    score
            ) a
    );