There is a table called user
which structure is like so:
id | ... | qq_unionid | wx_unionid
1 | ... | nfdufdflfl | fdfgnugdgdll
2 | ... | NULL | dfdfjjdfjd
3 | ... | fdfnfdfull | NULL
4 | ... | NULL | NULL
Now, what i want to do is move the two fields qq_unionid
and wx_unionid
into another table thirdpartyinfo
whick looks like so:
id | user_id | qq_nickname | wx_nickname
1 | 1 | Petter | Petter
2 | 2 | null | Gorgine
3 | 3 | Julia | NULL
and what i expected is like below:
id | user_id | qq_unionid | wx_unionid | qq_nickname | wx_nickname
1 | 1 | dfdfdj | fdjfkjdd | Petter | Petter
2 | 2 | NULL | fdjkfjd | NULL | Gorgine
3 | 3 | dfdfdfdff | NULL | Julia | NULL
I do not know how to write SQL statement to move the two fields into new table. Please give me a hand. Thanks so much.
You can SELECT
the information without moving the columns to the other table. You can also use this query to create a view .
SELECT t.id, t.user_id, u.qq_unionid, u.wx_unionid, t.qq_nickname, t.wx_nickname
FROM thirdpartyinfo t INNER JOIN `user` u ON t.user_id = u.id
In case you want to create new columns on table thirdpartyinfo
and set the values from user
into the new columns you can do the following:
ALTER TABLE thirdpartyinfo ADD COLUMN qq_unionid VARCHAR(255) NULL,
ADD COLUMN wx_unionid VARCHAR(255) NULL
The two columns are available now in the thirdpartyinfo
table. Make sure you are using the correct / needed column definition. After that you can set the values from user
table to the new columns, using UPDATE
:
UPDATE thirdpartyinfo INNER JOIN `user` ON thirdpartyinfo.user_id = `user`.id
SET thirdpartyinfo.qq_unionid = `user`.qq_unionid,
thirdpartyinfo.wx_unionid = `user`.wx_unionid
If I understand correctly, what you want is to make thirdpartyinfo
table having 2 new fields (ie qq_unionid, wx_unionid) and fill these 2 fields with data from user
table.
First of all, you need to create those 2 new columns in the thirdpartyinfo
table:
ALTER TABLE thirdpartyinfo ADD qq_unionid varchar(40) NULL, ADD wx_unionid varchar(40) NULL
Next you can use MERGE
to fill in the data from user
table:
MERGE INTO thirdpartyinfo target
USING (SELECT u.id, u.qq_unionid, u.wx_unionid FROM user u) source
ON (target.id=source.id)
WHEN MATCHED THEN
UPDATE
SET target.qq_unionid = source.qq_unionid,
target.wx_unionid = source.wx_unionid;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.