mysql向一列插入多列数据

mysql insert multiple column data to one column

您好,我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='Whosebug';

结果

questid user_id  userid  userid userid

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

我如何将列值插入另一个 table 像

这样的列
userids
   4
   3
   null
   5
   1
   4
   8
   6
  76
   7
  21
  23

有什么建议吗?谢谢

首先,让我们删除所有不必要的子查询,使查询更标准一些:

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='Whosebug';

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

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

可能有一些方法可以避免 qw.word='Whosebug' 4 次,但现在我没有灵感...

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

另请注意,您在 user_iduserid 中有点不一致 - 我开始清理它,然后意识到它实际上可能在您的表中,因此您可能必须这样做我的打扫卫生稍微打扫一下。