2012-10-17 35 views
0
SELECT 
*, 
(SELECT 
GROUP_CONCAT(url SEPARATOR '$$') 
FROM project_photos 
WHERE project_id = projects.id 
ORDER BY priority) AS images 
FROM projects 
WHERE catID = 2 
LIMIT 0,5 

上述查詢工作正常,但images coloumn是沒有順序的優先級,無法理解爲什麼它正在發生使用ORDER BYGROUP_CONCAT與ORDER BY,但是結果並不能orderd

// Structure for table project is 
CREATE TABLE `projects` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`catID` int(11) NOT NULL, 
`title` varchar(255) NOT NULL, 
`description` varchar(400) NOT NULL, 
`url` varchar(255) DEFAULT NULL, 
`tags` varchar(255) DEFAULT NULL, 
`featured` varchar(3) NOT NULL DEFAULT 'No', 
`featured_url` varchar(255) DEFAULT NULL, 
`order` int(11) DEFAULT NULL, 
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 
PRIMARY KEY (`id`), 
KEY `catID` (`catID`), 
CONSTRAINT `FK_catID` FOREIGN KEY (`catID`) REFERENCES `category` (`catID`) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=latin1; 


// Structure for table project_photos is 

CREATE TABLE `project_photos` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`url` varchar(250) DEFAULT NULL, 
`project_id` int(11) DEFAULT NULL, 
`priority` int(11) DEFAULT NULL, 
PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=347 DEFAULT CHARSET=utf8; 

回答

4

訂購完成之後應用聚合函數,如GROUP_CONCAT()。要排序的GROUP_CONCAT()結果把它的參數內:

SELECT 
GROUP_CONCAT(url ORDER BY priority SEPARATOR '$$') 
FROM project_photos 
WHERE project_id = projects.id 
2

嘗試使用ORDER BYGROUP_CONCAT

SELECT 
*, 
(SELECT 
GROUP_CONCAT(url ORDER BY priority SEPARATOR '$$') 
FROM project_photos 
WHERE project_id = projects.id 
) AS images 
FROM projects 
WHERE catID = 2 
LIMIT 0,5 
2

裏面你應該把order by子句組CONCAT內:

GROUP_CONCAT(url SEPARATOR '$$' ORDER BY priority) 

外部的order by訂購不同的行。既然你只有一個,它什麼都不做。在組concat中,它將命令由group by子句創建的組的元素。