2011-04-07 234 views
0

我有兩個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 

如何編寫合併的輸出一個QUERTY首先查詢到由「\」分隔的第二個查詢的PATH列中?這可能嗎?

回答

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 
+0

尼斯。如果我將「3」切換到ImageTable.folderId,我就快到了。但是,如何將「1,2」切換到FolderTable.path? – GuruMeditation 2011-04-07 12:35:35

+0

我還沒有看到'FOLDER_ID'...我想FolderTable中的文件夾路徑以'ImageTable.FOLDER_ID'結尾,並且以最近的null PATH' ImageTable.FOLDER_ID'開始? – manji 2011-04-07 12:49:04

0

查找到INNER JOIN

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

您可以連接字段連同 「\」,如果你想

相關問題