mysql - 长查询中重复子查询的替代方法

时间:2012-09-13 10:24:35

标签: mysql subquery

我将一个表的一行插入到另一个表中,为此我有一个像

这样的查询
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'

如果需要更多详细信息,请与我们联系。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

了解SQL joins

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