Is it possible to use SELECT after WHERE

时间:2015-06-25 19:16:10

标签: sql sqlite

I have 2 tables: 1 master table and 1 that I'm trying to put together. TABLE1: ID (AUTOINCREMENT) NAME PARENT TABLE2: ID(AUTOINCREMENT) PARENT CHILD SQL code: INSERT INTO TABLE2 (PARENT, CHILD) SELECT TABLE1.PARENT, TABLE1.ID FROM TABLE1 WHERE TABLE1.PARENT = (SELECT DISTINCT TABLE1.PARENT FROM TABLE1) So I want my query to go over all the PARENTs and one by one get all its children. Obviously it's not working and it is returning only the first PARENT and its children IDs

2 个答案:

答案 0 :(得分:3)

是的,您可以使用IN代替=

试试这个:

INSERT INTO TABLE2 (PARENT, CHILD) 
SELECT TABLE1.PARENT, TABLE1.ID 
FROM TABLE1
WHERE TABLE1.PARENT IN (SELECT DISTINCT TABLE1.PARENT FROM  TABLE1)

答案 1 :(得分:1)

该查询将产生与更简单的结果完全相同的结果:

INSERT INTO TABLE2 (PARENT, CHILD)
SELECT PARENT, ID
FROM TABLE1

where子句中的子查询无效。它基本上是说,请从表1中插入父和id,其中父和id在表1中。它们都将是。

现在,如果您在子查询中使用单独的表,这可能有意义。但即便如此,我建议只是这样加入:

INSERT INTO TABLE2 (PARENT, CHILD) 
SELECT TABLE1.PARENT, TABLE1.ID 
FROM TABLE1
JOIN 
(SELECT DISTINCT PARENT FROM TABLE2) TABLE2
ON TABLE1.PARENT = TABLE2.PARENT