除了MySQL之外,其他任何事情都很简单。
基本上我需要根据特定术语返回的结果来切换我正在使用的索引类型以及一些其他条件。
产生效果:
IF (SELECT COUNT(*) FROM table WHERE term LIKE "term") > 4000
EXECUTE QUERY A
ELSE
EXECUTE QUERY B
这是否可以在MySQL语句中使用?
编辑:
查询A:
SELECT id
FROM table_a
FORCE INDEX(id)
JOIN table_b ON table_a.id = table_b.id
WHERE term LIKE "term"
ORDER BY date
LIMIT 100;
查询B:
SELECT id
FROM table_a
FORCE INDEX(term)
JOIN table_b ON table_a.id = table_b.id
WHERE term LIKE "term"
GROUP BY term # These lines would be included for a few conditions not mentioned above.. but are necessary
HAVING COUNT = 1 # same...
ORDER BY date
LIMIT 100;
查询切换的原因是我根据“术语”的流行度得到了截然不同的结果时间。
答案 0 :(得分:18)
编辑:我在下面说的关于要求存储过程的内容是不正确的。试试这个:
SELECT CASE WHEN ( (SELECT COUNT(*) FROM table WHERE term LIKE "term") > 4000 )
THEN <QUERY A>
ELSE <QUERY B>
END
这确实是一个案例表达式,它在存储过程之外工作正常: - )
例如:
mysql> SELECT CASE WHEN ( 5 > 4 ) THEN ( SELECT 'foo' ) ELSE ( SELECT 'bar' ) END;
+---------------------------------------------------------------------+
| CASE WHEN ( 5 > 4 ) THEN ( SELECT 'foo' ) ELSE ( SELECT 'bar' ) END |
+---------------------------------------------------------------------+
| foo |
+---------------------------------------------------------------------+
1 row in set (0.01 sec)
mysql> SELECT CASE WHEN ( 3 > 4 ) THEN ( SELECT 'foo' ) ELSE ( SELECT 'bar' ) END;
+---------------------------------------------------------------------+
| CASE WHEN ( 3 > 4 ) THEN ( SELECT 'foo' ) ELSE ( SELECT 'bar' ) END |
+---------------------------------------------------------------------+
| bar |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)
以下旧答案的历史兴趣,因为它已经收集了赞成票:
你可以使用下面我想的,但只能在存储过程中使用:
CASE (SELECT COUNT(*) FROM table WHERE term LIKE "term") > 4000
WHEN 1 THEN <QUERY A>
ELSE <QUERY B>
END CASE
这是一个CASE
语句,与CASE
表达式不同... https://dev.mysql.com/doc/refman/5.0/en/case.html有更多血腥的细节。
实际上,我一般怀疑如果你想有条件地执行不同的查询,你需要查看存储过程 - 我可能是错的,但这是我的直觉。如果你能做到,那可能就是CASE表达式!
最后一个编辑:在任何现实世界的例子中,我可能会在我的应用程序中执行条件位,并且在我决定搜索什么后,只需将其移交给SQL(或生成我的SQL的ORM)对
答案 1 :(得分:4)
尝试:
select coalesce(i.id, t.id) id
from (SELECT COUNT(*) countterm FROM table WHERE term LIKE "term") c
left join
(SELECT id, date
FROM table_a
FORCE INDEX(id)
JOIN table_b ON table_a.id = table_b.id
WHERE term LIKE "term") i on countterm > 4000
left join
(SELECT id, date
FROM table_a
FORCE INDEX(term)
JOIN table_b ON table_a.id = table_b.id
WHERE term LIKE "term"
GROUP BY term
HAVING COUNT = 1) t on countterm <= 4000
ORDER BY coalesce(i.date, t.date)
LIMIT 100;