I have the following problem: I have 'content' table, which keeps main posts and objects in the system, 'custom_field' table, which enables use to add any custom field to a post and 'content_data' table, which holds custom field values.
CREATE TABLE `cms_content` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `cms_content_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`custom_field_id` int(11) NOT NULL,
`value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`content_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `key` (`value`,`content_id`,`custom_field_id`) USING BTREE,
KEY `content_id` (`content_id`),
KEY `custom_field_id` (`custom_field_id`),
KEY `value` (`value`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `cms_custom_field` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_2` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Now, I want to be able to ORDER result set BY custom field value. Both custom_field.name column and content_data.value column are indexed, but that does not seem to help and the query is very slow. content_data.custom_field_id is certainly indexed as well.
Here's my query:
SELECT `content`.`id`, `content_data`.`value` AS `title_sort`
FROM `content`
INNER JOIN `content_data` ON `content_data`.`content_id` = `content`.`id`
LEFT JOIN `custom_field` ON `custom_field`.`id` = `content_data`.`custom_field_id`
WHERE `custom_field`.`name` = 'title_sort'
ORDER BY `title_sort`
Is there any way to do it in a more optimized way?
Thank you in advance!
I want to be able to ORDER result set BY custom field value. Both custom_field.name column and content_data.value column are indexed
You have entitled content_data.value
as the column to sort by. That is a varchar(255) column. The real 'title_sort' is an indexed varchar(50) column from custom_field.name
.
This is closer to your described requirement:
SELECT
`content`.`id`
, `custom_field`.`name` AS `title_sort`
, `content_data`.`value`AS whatever_this_is
FROM `custom_field`
INNER JOIN `content_data` ON `custom_field`.`id` = `content_data`.`custom_field_id`
INNER JOIN `content` ON `content_data`.`content_id` = `content`.`id`
WHERE `custom_field`.`name` = 'title_sort'
ORDER BY `custom_field`.`name`
However, what you do want is very probably a sort on content_data
. value
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.