克隆表包括多个pk

时间:2016-04-25 08:40:39

标签: mysql

我想通过这些陈述将一张桌子克隆到另一张桌子上:

INSERT clone_table1
SELECT alias.* FROM table1 alias
INNER JOIN table2 b
on alias.pidm = b.user
WHERE alias.pidm LIKE "2016%"
AND b.userstate = 30;

是的,它确实有效,直到alias.pidm上有多个table1

表1:

id | pidm | field1 | field2
---------------------------
 1 |   5  |   aa   |  bb
 2 |   5  |   cc   |  dd
 3 |   5  |   ee   |  ff

表2:

user | field1 | userstate
-------------------------
 5   |   kk   |    30
 6   |   jj   |    40

因此,我可以识别的唯一字段位于table1.pidmtable2.user之间。

所以问题是:如何将所有where table1.pidm=5 and table2.userstate=30行插入clone_table1

提前致谢。

3 个答案:

答案 0 :(得分:1)

INSERT clone_table1
SELECT alias.* FROM table1 alias
LEFT JOIN table2 b
on alias.pidm = b.user AND b.userstate = 30
WHERE alias.pidm LIKE "2016%"

答案 1 :(得分:1)

INSERT clone_table SELECT * FROM table1 WHERE table1.pidm=5 AND table2.userstate = (SELECT * FROM table2 WHERE table2.userstate=30) not sure if it will work but you can try using sub-queries. It's been too long since i touch on sql. Here is the link that might help

答案 2 :(得分:0)

我已经解决了查询问题如下:

INSERT clone_table1
SELECT alias.* FROM table1 alias
INNER JOIN table2 b
on alias.pidm = b.user
WHERE alias.pidm LIKE "2016%"
AND b.userstate= 30;

感谢。