从select语句插入的mysql只插入零

时间:2014-03-08 22:03:28

标签: mysql select insert

我正在尝试在表中插入一个新行,其中包含来自不同表的select语句的计数。当我运行以下命令时,它会创建行,但是使用select语句为两个字段插入0(而不是单独运行select语句时得到的值1047和8)。我尝试将select语句放在insert语句中,但这会引发错误。我出错的地方有什么帮助吗?提前谢谢。

select count(*) from research.Neuro_Recruited_MG as letters_sent;
select count(*) from research.neuro_subject_log s where s.enrolled like 'PS' as pending_screening;
insert into neuro_stats (id, letters_sent, pending_screening)
values (3, 'letters_sent','pending_screening’)

2 个答案:

答案 0 :(得分:1)

您正在运行三个单独的语句。前两个(SELECT)执行,但开始下一个丢弃它之前的那个。

尝试这样的事情:

insert into neuro_stats 
  (id, letters_sent, pending_screening)
values 
  (3, 
   (select count(*) from research.Neuro_Recruited_MG),
   (select count(*) from research.neuro_subject_log s where s.enrolled like 'PS'));

答案 1 :(得分:0)

尝试,假设id为auto_increment。

insert neuro_stats(letters_sent, pending_screening)
select sum(count_letters_sent), sum(count_pending_Screening)
from (
  select count(*) as count_letters_sent, 0 as count_pending_screening) 
  from research.neuro_recruited_MG
  UNION
  select 0 as count_letters_sent, count(*) as count_pending_screening
  from reserach.neuro_subject_log as s
  where s.enrolled like '%PS%'
) as xcount;

可能是你的喜欢'PS'在'PS'之前和/或之后需要通配符%,实际上是搜索“开头”,“包含”或“结束”与'PS'