MySQL - 将第一个查询结果合并到第二个查询的列中

时间:2011-04-07 12:18:53

标签: mysql

我有两个MySQL表,我想知道是否有任何方法可以合并第一个查询的结果,以便它们在第二个查询中显示为一列。这是一个例子:

表1

FolderTable

ID  NAME    PATH
1    c: 
2    tmp     1
3     test    1,2

SELECT name FROM FolderTable WHERE id IN (1, 2, 3)
Result:
c:
tmp
test

表2

ImageTable

ID  NAME        FOLDER_ID
1    hi.jpg       3
2    blah.jpg     3
3    overwlow.jpg 3

SELECT name FROM ImageTable WHERE id = 2
Result:
NAME
blah.jpg

我想要什么:

Result:
NAME        PATH
blah.jpg    c:\tmp\test

如何编写将第一个查询的输出合并到由“\”分隔的第二个查询的PATH列的querty?这可能吗?

2 个答案:

答案 0 :(得分:1)

SELECT name,
       SELECT GROUP_CONCAT(name ORDER BY ID SEPARATOR '\')
         FROM FolderTable 
        WHERE id BETWEEN (SELECT MAX(ID)
                            FROM FolderTable
                           WHERE ID < ImageTable.FOLDER_ID
                             AND PATH IS NULL) 
                     AND ImageTable.FOLDER_ID
 FROM ImageTable WHERE id = 2

答案 1 :(得分:0)

了解INNER JOIN

SELECT 
    FolderTable.Name AS FolderName, ImageTable.Name AS ImageName 
FROM 
    FolderTable 
INNER JOIN 
    ImageTable ON ImageTable.FolderId = FolderTable.ID

如果您愿意,可以将字段与“\”连接在一起