我正在开发一个系统,您可以在其中按颜色搜索和订购产品。我今天有一个查询,但是当集合中有很多产品时它很慢。有没有人有解决办法让它更有效?
表格:
* = index
**products**
+------------+----------+
| id_product*| id_image*|
+------------+----------+
| 1 | 5 |
| 2 | 8 |
| 3 | 3 |
| 4 | 9 |
| 5 | 2 |
| ...... | ...... |
+------------+----------+
// and some more product data, only these columns used in this query
**image_rgb**
+----------+--------------+-------------+
| id_image*| id_rgb_color*| dominance |
+----------+--------------+-------------+
| 23016 | 242 | 0.119562465 |
| 590855 | 16 | 0.042380076 |
| 605196 | 1 | 0.062330416 |
| 8436 | 146 | 0.063439071 |
| 68452 | 30 | 0.103740936 |
| ..... | ..... | ........... |
+----------+--------------+-------------+
// dominance not in use for now, havent't figured out a good way to implement this yet
**rgb_colors**
+--------+-----+-----+-----+
| id_rgb*| r* | g* | b* |
+--------+-----+-----+-----+
| 1 | 240 | 240 | 230 |
| 2 | 230 | 210 | 190 |
| 3 | 230 | 220 | 210 |
| 4 | 220 | 200 | 180 |
| 5 | 250 | 250 | 250 |
| ... | ... | ... | ... |
+--------+-----+-----+-----+
**product_categories**
+------------+-------------+
| id_product*| id_category*|
+------------+-------------+
| 1 | 35 |
| 2 | 15 |
| 3 | 8 |
| 4 | 39 |
| 5 | 61 |
| ..... | ..... |
+------------+-------------+
查询:
$r = 150;
$g = 100;
$b = 170;
$categories = '1,2,3,4,5,6,7,8,9,.....';
SELECT a.id_product,
(SELECT
min
(
ABS(rgb_colors.r - $r) + // passing in red value
ABS(rgb_colors.g - $g) + // passing in green value
ABS(rgb_colors.b - $b) // passing in blue value
) clrDiff // finding the closest match - 0 is exact match
FROM image_rgb
JOIN rgb_colors ON rgb_colors.id_rgb = image_rgb.id_rgb_color
WHERE image_rgb.id_image = a.id_image
) clrDiff
FROM products a
JOIN product_categories b ON b.id_product = a.id_product
WHERE
product_categories.id_category IN ($categories)
GROUP BY a.id_product
ORDER BY clrDiff DESC
LIMIT 48
OFFSET 0
结果:
+------------+-------------+
| id_product*| clrDiff |
+------------+-------------+
| 1 | 0 |
| 2 | 5 |
| 3 | 8 |
| 4 | 13 |
| 5 | 28 |
| ..... | ..... |
+------------+-------------+
这个查询给出了一个很好的结果,但它很慢,需要几秒钟,大约有50.000个产品。已经尝试了一些替代方案,但它们要么更慢,要么得不到足够好的结果。