mysql将多列数据插入一列

时间:2015-03-10 14:14:27

标签: mysql insert left-join

嗨,我有这样的mysql查询

Select  postid, user_id , qfav.userid, qfeed.userid, qview.userid  
from post_words as qw 
left join (Select userid, postid as postidfav  from post_favorite) as  qfav 
    on qfav.questidfav=qw.questid 
left join (Select userid, questid as questidfeed from post_feedback) as  qfeed 
    on qfeed.questidfeed=qw.questid 
left join (Select userid, questid as questidview from post_stats_view) as qview 
    on qview.questidview=qw.questid 
where qw.word='stackoverflow';

结果

questid user_id  userid  userid userid

 100       4       3      null    5
  25       1       4       8      6
 200       76      7       21     23

我如何将列值插入另一个表,如

userids
   4
   3
   null
   5
   1
   4
   8
   6
  76
   7
  21
  23

有什么建议吗?感谢

1 个答案:

答案 0 :(得分:2)

首先,让我们通过删除所有不必要的子查询来使查询更加标准化:

Select  postid, user_id , qfav.userid, qfeed.userid, qview.userid  
from post_words as qw 
left join post_favorite as qfav 
    on qfav.questidfav=qw.questid 
left join post_feedback as qfeed
    on qfeed.questidfeed=qw.questid 
left join post_stats_view as qview
    on qview.questidview=qw.questid 
where qw.word='stackoverflow';

然后我们将使用userid将所有UNION列放入一个列中,并在前面添加一个INSERT:

INSERT INTO SomeTable (userid) 
Select  userid
  from post_words as qw 
  where qw.word='stackoverflow'
UNION
Select  qfav.userid
  from post_words as qw 
  left join post_favorite as qfav 
    on qfav.questidfav=qw.questid 
  where qw.word='stackoverflow'
UNION
Select  qfeed.userid
  from post_words as qw 
  left join post_feedback as qfeed
    on qfeed.questidfeed=qw.questid 
  where qw.word='stackoverflow'
UNION
  Select  qview.userid  
  from post_words as qw 
  left join post_stats_view as qview
    on qview.questidview=qw.questid 
  where qw.word='stackoverflow';

可能有一些方法可以避免不得不进行qw.word='stackoverflow' 4次,但现在没有任何灵感来打击我......

确保您的SomeTable不需要唯一的user_id列。

另请注意,user_id vs userid中你有点不一致 - 我开始清理它然后意识到它可能实际上在你的桌子里,所以你可能需要做一点清理我的清洁工作。