我有一个带日期的表和一些带整数的字段,如下所示:
SELECT * FROM numbers LIMIT 10;
+----+------------+----+----+----+----+----+----+----+
| id | gen_date | n1 | n2 | n3 | n4 | n5 | n6 | n7 |
+----+------------+----+----+----+----+----+----+----+
| 1 | 1990-12-27 | 22 | 43 | 18 | 23 | 16 | 7 | 0 |
| 2 | 1990-12-19 | 39 | 11 | 38 | 23 | 24 | 36 | 0 |
| 3 | 1990-12-12 | 44 | 12 | 10 | 48 | 14 | 4 | 0 |
| 4 | 1990-12-05 | 2 | 4 | 5 | 46 | 48 | 49 | 0 |
| 5 | 1991-12-25 | 10 | 2 | 44 | 49 | 29 | 34 | 0 |
| 6 | 1991-12-18 | 6 | 19 | 42 | 4 | 12 | 28 | 0 |
| 7 | 1991-12-11 | 1 | 12 | 42 | 7 | 31 | 25 | 0 |
| 8 | 1991-12-04 | 18 | 47 | 31 | 30 | 10 | 35 | 0 |
| 9 | 1991-11-27 | 38 | 33 | 39 | 47 | 13 | 11 | 0 |
| 10 | 1991-11-20 | 23 | 7 | 22 | 18 | 43 | 16 | 0 |
+----+------------+----+----+----+----+----+----+----+
所有行号都是唯一的nx <> ny
。
我希望将一组6个数字与列n1 to n6
相匹配,无论是值序还是。
例如,在ID=1
的行中有22, 43, 18, 23, 16, 7
,而ID=10
的行具有相同的数字23, 7, 22, 18, 43, 16
。我已经在每行中写了一个查询,其中包含每行列集中的所有数字。如果我需要搜索数字7, 16, 18, 22, 23, 43
,则结果会返回ID=1
行和ID=10
行。
我通过使用FIELD
函数在所有字段值中搜索每个数字来实现它:
SELECT * FROM numbers
WHERE
FIELD(7, n1, n2, n3, n4, n5, n6) > 0 AND
FIELD(16, n1, n2, n3, n4, n5, n6) > 0 AND
FIELD(18, n1, n2, n3, n4, n5, n6) > 0 AND
FIELD(22, n1, n2, n3, n4, n5, n6) > 0 AND
FIELD(23, n1, n2, n3, n4, n5, n6) > 0 AND
FIELD(43, n1, n2, n3, n4, n5, n6) > 0;
+----+------------+----+----+----+----+----+----+----+
| id | gen_date | n1 | n2 | n3 | n4 | n5 | n6 | n7 |
+----+------------+----+----+----+----+----+----+----+
| 1 | 1990-12-27 | 22 | 43 | 18 | 23 | 16 | 7 | 0 |
| 10 | 1991-11-20 | 23 | 7 | 22 | 18 | 43 | 16 | 0 |
+----+------------+----+----+----+----+----+----+----+
这很有效,但是我对它的工作方式有一些担忧,如果使用这种方法在使用成千上万行的时候是明智的话。
是否还有其他更好的(或更简单的)方式来完成这样的事情?
答案 0 :(得分:2)
您的查询可以简化为:
SELECT *
FROM numbers
WHERE
7 IN (n1, n2, n3, n4, n5, n6) AND
16 IN (n1, n2, n3, n4, n5, n6) AND
18 IN (n1, n2, n3, n4, n5, n6) AND
22 IN (n1, n2, n3, n4, n5, n6) AND
23 IN (n1, n2, n3, n4, n5, n6) AND
43 IN (n1, n2, n3, n4, n5, n6) ;