INSERT SELECT query when one column is unique

社会主义新天地 提交于 2019-12-11 03:21:31

问题


I need to call INSERT + SELECT to import user data to different table and I need to filter user_name duplications, So I need something like this:

INSERT INTO new_table SELECT email, distinct user_name, password from old_table

but distinct works only when using distinct email, user_name, password and all those column need to be unique.

Is there any other way to insert select with uniq user_names, (I need only first row - with lower id)?

EDIT I forget to mention that I use mysql


回答1:


Without testing I would expect something like this to do the trick (assuming the id column is named id)

INSERT INTO new_table 
    SELECT email, user_name, password 
    FROM old_table 
    INNER JOIN 
        ( SELECT MIN(id) FROM old_table GROUP by user_name ) minids
    ON minids.id = old_table.id


来源:https://stackoverflow.com/questions/11648568/insert-select-query-when-one-column-is-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!