【发布时间】:2022-01-25 16:14:58
【问题描述】:
我正在尝试计算下表中的几个项目:
| food |
|---|
| apple cider |
| cake manzana (manzana in spanish == apple) |
| carrot cake |
| banana pudding |
我希望得到下表:
| food | count |
|---|---|
| apple | 2 |
| carrot | 1 |
| banana | 1 |
我尝试了以下查询apples:
SELECT 'apple' as placeholder, COUNT(*)
FROM table WHERE (food LIKE '%apple%' OR food LIKE '%manzana%') and date > '10/10/2021'
问题是当我尝试扩展它以将所有食物放在一起时,需要很长时间:
SELECT 'apple' as placeholder, COUNT(*) FROM table WHERE (food LIKE '%apple%' OR food LIKE '%manzana%') and date > '10/10/2021' and ...
UNION ALL
SELECT 'carrot' as placeholder, COUNT(*) FROM table WHERE food LIKE '%carrot%' and date > '10/10/2021' and ...
UNION ALL
SELECT 'banana' as placeholder, COUNT(*) FROM table WHERE food LIKE '%banana%' and date > '10/10/2021' and ...
还有其他方式来构造这个查询吗?
【问题讨论】:
-
我会责怪 LIKE 而不是 UNION ALL。
-
是的,需要时间,因为Like操作和表中的记录数。尝试将每个结果存储到 Temp 表中,然后合并 # 个表。
-
每个查询本身需要大约 9 秒,但是当我将它们与
UNION ALL一起添加时,它们需要更长的时间(已经过了几分钟,但还没有完成)@jarlh -
日期索引可能会有很大帮助。
标签: sql sql-server subquery