1

正在将一个表的一行插入到另一个表中,为此我有一个类似的查询

INSERT INTO table1 
        (id,name,fieldname,address) 
SELECT (SELECT id FROM usertable WHERE name = 'namevalue'),
        name,
       ( SELECT fieldname FROM fielddata WHERE id IN 
         (SELECT id FROM usertable  WHERE name = 'namevalue') ),
       address 
FROM   sourcetable 
WHERE  cond = 'value' 

在上面的查询中,下面的子查询重复了两次,有没有办法只使用一次子查询并保留该值并在其他地方使用它。

SELECT id FROM usertable WHERE name = 'namevalue'

让我知道是否需要更多详细信息。

4

2 回答 2

0

了解SQL 连接

INSERT INTO table1 (id, name, fieldname, address)
SELECT usertable.id,
       sourcetable.name,
       fielddata.fieldname,
       sourcetable.address
FROM   sourcetable
  JOIN usertable ON sourcetable.cond = 'value'
                AND usertable.name = 'namevalue'
  LEFT JOIN fielddata ON fielddata.id = usertable.id
于 2012-09-13T12:33:14.343 回答
0

尝试这个:

INSERT INTO table1 
    (id,name,fieldname,address) 
SELECT sub.id, 
   sub.name,
   ( SELECT fieldname FROM fielddata WHERE id IN sub.id ),
   sub.address
FROM
(
    SELECT (SELECT id FROM usertable WHERE name = 'namevalue') id,
        name,
        address 
    FROM sourcetable 
    WHERE cond = 'value' 
) sub
于 2012-09-13T10:33:24.633 回答