25

除了 MySQL 之外,它在任何地方都感觉非常简单。

基本上,我需要根据特定术语返回的结果数量来切换我使用的索引类型以及其他一些条件。

大意是:

IF (SELECT COUNT(*) FROM table WHERE term LIKE "term") > 4000
   EXECUTE QUERY A
ELSE
   EXECUTE QUERY B

这可能在 MySQL 语句中吗?

编辑:

查询一:

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;

查询切换的原因是根据“术语”的受欢迎程度,我得到了截然不同的结果时间。

4

2 回答 2

23

编辑:我在下面所说的关于需要存储过程的内容是不正确的。尝试这个:

SELECT CASE WHEN ( (SELECT COUNT(*) FROM table WHERE term LIKE "term") > 4000 )
    THEN <QUERY A>
    ELSE <QUERY B>
END

这确实是一个 case 表达式,它在存储过程之外可以正常工作:-)

例如:

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)。

于 2013-06-19T20:40:24.827 回答
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;
于 2013-06-19T19:49:49.073 回答