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没有优先排序,无法理解为什么会发生

// 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

3 回答 3

4

ORDER BY在应用聚合函数(GROUP_CONCAT(). GROUP_CONCAT()要对将其放入参数中的结果进行排序:

SELECT
GROUP_CONCAT(url ORDER BY priority SEPARATOR '$$')
FROM project_photos
WHERE project_id = projects.id
于 2012-10-17T09:07:16.873 回答
2

尝试ORDER BY在里面使用GROUP_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
于 2012-10-17T09:07:27.413 回答
2

您应该将该order by子句放在组 concat 中:

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

外面正在订购不同的order by行。因为你只有一个,所以它什么都不做。在组 concat 中,它将对该group by子句创建的组的元素进行排序。

于 2012-10-17T09:07:56.310 回答