如何在子查询中使用外部查询的列?

时间:2009-10-07 16:17:52

标签: sql mysql

我有一个包含库存记录的表和另一个包含描述每个库存记录的文档的表,如:

inventory (t1)
t1id        t1c1
1          desc1
2          desc2
3          desc3

documents (t2)
t2id    t2c1     t1id
1       doc1     1
2       doc2     1
3       doc3     2
4       doc4     3

所以我尝试这个查询,我得到一个错误,告诉我在子查询附近没有这样的列(t1.t1id)= s

SELECT t1c1,(SELECT GROUP_CONCAT(t2c1) FROM t2 WHERE t1.t1id = t2.t1id) FROM t1

任何想法?

2 个答案:

答案 0 :(得分:3)

这适用于5.05.1

CREATE TABLE t1 (t1id INT NOT NULL, t1c1 VARCHAR(20) NOT NULL);

CREATE TABLE t2 (t2id INT NOT NULL, t2c1 INT NOT NULL, t1id INT NOT NULL);

SELECT  t1c1,
        (
        SELECT  GROUP_CONCAT(t2c1)
        FROM    t2
        WHERE   t1.t1id = t2.t1id
        )
FROM    t1

您可以尝试将其重写为JOIN

SELECT  t1c1, GROUP_CONCAT(t2c1)
FROM    t1
LEFT JOIN
        t2
ON      t2.t1id = t1.t1id
GROUP BY
        t1.t1id

答案 1 :(得分:0)

您必须指定表名(文档,库存)

SELECT t1c1,  (SELECT GROUP_CONCAT(t2c1) 
               FROM documents t2 
               WHERE t1.t1id = t2.t1id) 
FROM inventory t1