我有 1,2,3,4,5,6,7,8,9,10 列,我想在所有这些编号的列中搜索一个特定值并且名称 = Bob
所以:
SELECT * FROM table WHERE name = BOB AND 1="value" OR 2="value" OR 3="value"
等等..
这样做最有效和最好的方法是什么?并且在列实际上像我的示例中那样编号的情况下,有没有办法在查询中建立索引以从 1-10 循环?
谢谢你。
而不是使用OR
use Union
。
像这样的东西: -
SELECT * FROM table WHERE name = BOB AND 1="value"
UNION
SELECT * FROM table WHERE name = BOB AND 2="value"
UNION
SELECT * FROM table WHERE name = BOB AND 3="value"
What would be the most efficient and best way of doing this?
SELECT * FROM table WHERE name = BOB AND `1`="value" OR `2`="value" OR `3`="value"
My bet is the above statement using OR
is probably one of your best choices.
There are (probably) several other variations. Anyway, you will have to compare them using EXPLAIN SELECT
to see if it perform better or worst -- depending on your particular data and indexes.
Just to conclude this "answer", here is one alternative solution. At the very least, more readable than a bunch or OR
...
SELECT * FROM table WHERE name = BOB AND "value" IN (`1`,`2`,`3`)
BTW, as I said in a comment above, 1
, 2
, 3
... are not good columns names. I won't repeat myself here, but here an transcription that shows why it is error prone, and what's going on when you write 1 = "hello"
:
mysql> SELECT True FROM DUAL WHERE 1 = "hello";
Empty set, 1 warning (0.00 sec)
mysql> SHOW WARNINGS;
+---------+------+-------------------------------------------+
| Level | Code | Message |
+---------+------+-------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: 'hello' |
+---------+------+-------------------------------------------+
1 row in set (0.00 sec)
mysql> EXPLAIN SELECT True FROM DUAL WHERE 1 = "hello";
+----+-------------+-----+------------------+
| id | select_type | ... | Extra |
+----+-------------+-----+------------------+
| 1 | SIMPLE | ... | Impossible WHERE |
+----+-------------+-----+------------------+
1 row in set, 1 warning (0.00 sec)