yupang
yupang

Reputation: 155

How to import data from one table to another in mysql

There're two tables in database

table users with some datas

username invitedby
123      23
12       45
89433    11893
faf      123
afsafgf  12

table list

lname  type

I want to import data from users to list, and the list data show like this

lname  type
123      3
12       3
89433    3
faf      3
afsafgf  3
123      2
12       2

First, import all datas into users, and lname is from username, and set the type to be 3.

Second, if some username inivited another, such as faf is invited by 123, afsafgf is invited by 12, insert the inviter and set its type to be 2, the last two line data above.

How can I write this SQL query in mysql? Many thanks.

Upvotes: 0

Views: 96

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269803

Is this what you want?

insert into list (lname, type)
    select username, 3
    from users
    union all
    select invitedby, 2
    from users u
    where exists (select 1 from users u2 where u2.username = u.invitedby);

Upvotes: 2

Related Questions