在MySQL中从同一列插入不同的值

时间:2016-05-20 06:46:54

标签: mysql

这可能是一个简单的问题,但我真的很困惑。

我需要这样的陈述:

    INSERT INTO `DB`.`converted_values` (`type`,`old_value`, `new_value`)
            SELECT 'USER_ID',`users`.`id` AS _OLD , `users`.`id` as _NEW
            FROM `DB`.`users`
            WHERE _OLD IN ( SELECT `id` FROM `DB`.`users` WHERE `level`=ORIGINAL_LEVEL) 
            AND _NEW IN ( SELECT `id` FROM `DB`.`users` WHERE `level`=NEW_LEVEL);

level不是唯一的,可能会返回N个结果,但_OLD_NEW的行数相同。

最终结果必须是这样的:

type    | old_value | new_value
USER_ID | 8         | 500
USER_ID | 17        | 507
USER_ID | 60        | 521
USER_ID | 81        | 890

感谢。

2 个答案:

答案 0 :(得分:0)

尝试不使用别名

      INSERT INTO `DB`.`converted_values` (`type`,`old_value`, `new_value`)
        SELECT  distinct 'USER_ID',`users`.`id`  , `users`.`id`  
        FROM `DB`.`users`
        WHERE `users`.`id`  IN ( SELECT `id` FROM `DB`.`users` WHERE `level`=ORIGINAL_LEVEL) 
        AND `users`.`id` IN ( SELECT `id` FROM `DB`.`users` WHERE `level`=NEW_LEVEL);

答案 1 :(得分:0)

/*
drop    table users;
CREATE TABLE users
(user_id VARCHAR(6),LEVEL VARCHAR(20), id INT);
truncate table users;
INSERT INTO users
VALUES
('USER-1','ORIGINAL' , 8),
('USER-2','ORIGINAL' , 17),
('USER-3','ORIGINAL' , 60),
('USER-4','ORIGINAL' , 61),
('USER-1','NEW' , 500),
('USER-2','NEW' , 507),
('USER-3','NEW' , 521),
('USER-1','NEW' , 600)
;
*/

select  u1.user_id,u1.id 'Old', u2.id 'New' 
from    users u1
join    users u2 on u2.user_id = u1.user_id
where   u1.id IN (SELECT MIN(id) FROM users WHERE level = 'ORIGINAL' and user_id = u1.user_id)
    AND u2.id IN (SELECT MAX(id) FROM users WHERE level = 'NEW' and user_id = u2.user_id)
order   by u1.user_id