我需要从项目列表中选择满足搜索条件的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秒才能执行。我确信有更好的方法可以做到。
答案 0 :(得分: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
答案 1 :(得分: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注入问题等 - 使用prepared statements。
最后,请参阅@ ypercube的评论;这也是一个好点,并将产生重大影响。