0

我需要从项目列表中选择 50 个满足搜索条件的项目。我还需要他们当前的销售数量。项目列表有超过 100 000 条记录

这就是我现在要做的:

SELECT 
  items.id,
  CONCAT(prod_codes.code,items.item) AS item,
  items.price,
  sold.count
FROM items
LEFT JOIN prod_codes ON items.prod_code_id=prod_codes.id
LEFT JOIN (
    SELECT COUNT(*) AS count,CONCAT(prod_code,part_num) AS part 
    FROM `sold_items` 
    WHERE 1 
    GROUP BY CONCAT(prod_code,part_num)
    ORDER BY count DESC
) AS sold ON sold.part=CONCAT(prod_codes.code,items.item)
WHERE active_status=1
AND CONCAT(items.prod_code,items.item) collate utf8_general_ci LIKE '%".$search_part."%' 
AND items.description collate utf8_general_ci LIKE '%".$search_desc."%'

ORDER BY items.item

LIMIT 50

但是这个查询需要 20 多秒才能执行。我确信有更好的方法来做到这一点。

4

2 回答 2

0

替换 WHERE 子句的这一部分

CONCAT(items.prod_code,items.item) collate utf8_general_ci LIKE '%".$search_part."%'

有了这个:

(items.prod_code collate utf8_general_ci LIKE '%".$search_part."%' OR items.item collate utf8_general_ci LIKE '%".$search_part."%')

该 CONCAT() 调用几乎肯定会使其陷入困境,因为它不能使用索引。

此外,您还有 SQL 注入问题等——使用准备好的语句

最后,请参阅@ypercube 的评论;这也是一个好点,会产生很大的影响。

于 2013-11-04T19:06:03.107 回答
0

您可以尝试以下方法,而不是嵌套子查询:

SELECT 
  items.id,
  CONCAT(prod_codes.code,items.item) AS item,
  items.price,
  COUNT(*) AS count
FROM items
LEFT JOIN prod_codes ON items.prod_code_id = prod_codes.id
LEFT JOIN sold_items sold ON sold.prod_code = prod_codes.code AND sold.part_num = items.item
WHERE active_status = 1
AND CONCAT(items.prod_code,items.item) collate utf8_general_ci LIKE '%".$search_part."%' 
AND items.description collate utf8_general_ci LIKE '%".$search_desc."%'
ORDER BY items.item
GROUP BY prod_codes.code, items.item, items.id, items.price
LIMIT 50
于 2013-11-04T18:55:40.923 回答