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;
答案 0 :(得分:4)
使用ORDER BY
进行排序是在应用GROUP_CONCAT()
等聚合函数后完成的。要对GROUP_CONCAT()
的结果进行排序,请将其放入参数中:
SELECT
GROUP_CONCAT(url ORDER BY priority SEPARATOR '$$')
FROM project_photos
WHERE project_id = projects.id
答案 1 :(得分: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
答案 2 :(得分:2)
您应该将order by
子句放在组concat中:
GROUP_CONCAT(url SEPARATOR '$$' ORDER BY priority)
order by
外部正在排序不同的行。由于你只有一个,它什么都不做。在组concat中,它将命令由group by
子句创建的组的元素。