我花了几个小时制作一个 SQL 查询,该查询执行 JOIN
并将两列放在一起,以一种我以前从未处理过的方式。这是查询:
SELECT `m`.`id`, `m`.`primary_category_id`, `m`.`primary_category_priority`, `m`.`description`
FROM (`merchant` AS m)
LEFT JOIN `merchant_category`
ON `merchant_category`.`merchant_id` = `m`.`id`
WHERE
`merchant_category`.`category_id` = '2'
OR `m`.`primary_category_id` = '2'
GROUP BY `m`.`id`
ORDER BY
LEAST(merchant_category.priority = 0, `primary_category_priority` = 0) ASC,
LEAST(merchant_category.priority, `primary_category_priority` ) ASC
LIMIT 10
它必须对两列一起排序,一列来自merchant_category 表,一列来自merchant 表,以便将它们排序在一起。 merchant
的每一行都有一个“主要”类别(直接在表中引用)和零个或多个“次要”类别,存储在 merchant_category
表中。现在它工作正常,但速度非常慢:在我的生产数据库上通常需要一分钟多一点。我想 JOIN
加上复杂的排序导致了问题,但我能做什么?
编辑以下是两个表的架构:
CREATE TABLE IF NOT EXISTS `merchant` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) CHARACTER SET utf8 NOT NULL,
`primary_category_id` int(11) NOT NULL,
`primary_category_priority` int(10) unsigned NOT NULL DEFAULT '0',
`description` mediumtext CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `merchant_category` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`merchant_id` int(10) NOT NULL,
`category_id` int(10) NOT NULL,
`priority` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
最佳答案
尝试在第二个表上添加外键约束,
CREATE TABLE IF NOT EXISTS `merchant_category` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`merchant_id` int(10) NOT NULL,
`category_id` int(10) NOT NULL,
`priority` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
CONSTRAINT mc_fk FOREIGN KEY (`merchant_id`) REFERENCES `merchant`(`id`)
)
关于mysql - 加入/排序运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12468958/