在INSERT查询中使用SELECT

时间:2011-10-15 19:29:46

标签: mysql

请任何人都可以发现这个查询有什么问题。它给出了错误但我无法真正看到错误的来源,因为它没有真正指定

mysql>

insert into sorting (mindlrid,maxdlrid)
values (
   (select min(dlrid) 
   from dlr 
   where sid=
     (select distinct(s.sendid)
      from sent s
           ,dlr d
      where s.uid=d.uid
      and d.d_billed=1
      and d.d_sent=0 
      and s.processed=1
      and s.sendid=d.sid
      order by s.sendid asc
      limit 1))
  ,(select max(dlrid)
    from dlr
    where sid=(
       select distinct(s.sendid)
       from sent s,dlr d
       where s.uid=d.uid
       and d.d_billed=1
       and d.d_sent=0
       and s.processed=1
       and s.sendid=d.sid
       order by s.sendid asc 
     limit 1)
   );
  

错误1064(42000):您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行的''附近使用正确的语法

2 个答案:

答案 0 :(得分:0)

你错过了一个右括号。可能在insert的最后。等价:values子句上有一个额外的开头表。

INSERT INTO sorting
            (mindlrid,
             maxdlrid)
VALUES      (SELECT Min(dlrid)
              FROM   dlr
              WHERE  sid = (SELECT DISTINCT( s.sendid )
                            FROM   sent s,
                                   dlr d
                            WHERE  s.uid = d.uid
                                   AND d.d_billed = 1
                                   AND d.d_sent = 0
                                   AND s.processed = 1
                                   AND s.sendid = d.sid
                            ORDER  BY s.sendid ASC
                            LIMIT  1)),
             (SELECT Max(dlrid)
              FROM   dlr
              WHERE  sid = (SELECT DISTINCT( s.sendid )
                            FROM   sent s,
                                   dlr d
                            WHERE  s.uid = d.uid
                                   AND d.d_billed = 1
                                   AND d.d_sent = 0
                                   AND s.processed = 1
                                   AND s.sendid = d.sid
                            ORDER  BY s.sendid ASC
                            LIMIT  1)); 

答案 1 :(得分:0)

您可以直接使用SELECT的结果,无需将其包装到VALUES子句中:

insert into sorting (mindlrid,maxdlrid)
select min(dlrid), max(dlrid)
from dlr 
where sid=
     (select distinct s.sendid
      from sent s
           ,dlr d
      where s.uid=d.uid
      and d.d_billed=1
      and d.d_sent=0 
      and s.processed=1
      and s.sendid=d.sid
      order by s.sendid asc
      limit 1)

请注意DISTINCT不是函数。它是一个包含SELECT列表的所有列的运算符。