尝试在表中找到可存在于Field1或Field2或Field3中的特定值...(等等)

时间:2009-11-27 16:23:02

标签: sql

我有一个电话清单,我必须看看它们是否存在于表格“电话”中,问题是每个值可以在表格中有多个字段,即

此值: 4164553627 可以在Field1或Field2或Field3或Field4 ...或Field25

此值: 9054558557 可以在Field1或Field2或Field3或Field4 ...或Field25

是否有查询可以告诉我该值在哪个字段中?

4 个答案:

答案 0 :(得分:0)

这只会显示一个答案,(如果值可以在多个字段中,它只显示它找到值的第一个字段,而不是所有字段......但它应该给你一个开始。 ..

Select 
   Case '4164553627'
     When Field1 then 'F1'
     When Field2 then 'F2'
     ...
     When Field23 then 'F23'
     When Field24 then 'F24'
     When Field25 then 'F25' End as Field
From Table

答案 1 :(得分:0)

MySQL

SELECT  (field1 = '4164553627') |
        (field2 = '4164553627') << 1 |
        (field3 = '4164553627') << 2
        AS bitmap
FROM    mytable
HAVING  bitmap > 0

这将返回一个字段位图,其中包含为保存值的字段设置的位。

答案 2 :(得分:0)

之前我用过同样的问题。这有点残酷,但它会计算与第二个表匹配的每个字段中数字的出现次数。

SELECT Phone, SUM(F1) AS F1_COUNT, SUM(F2) AS F2_COUNT, ... SUM(F25) AS F25_COUNT
FROM (
  SELECT Table2.Number AS Phone, COUNT(Field1) AS F1, 0 AS F2, ... 0 AS F25
  FROM Table, Table2
  WHERE Field1 = Number
  UNION
  SELECT Table2.Number AS Phone, 0 AS F1, COUNT(Field2) AS F2, ... 0 AS F25
  FROM Table, Table2
  WHERE Field1 = Number
  UNION
  .
  .
  .
  SELECT Table2.Number AS Phone, 0 AS F1, 0 AS F2, ... COUNT(Field25) AS F25
  FROM Table, Table2
  WHERE Field1 = Number
)
GROUP BY Phone, F1_COUNT, F2_COUNT, ... F25_COUNT

答案 3 :(得分:0)

从表中选择解码(Field1,4164553627,'Field1',解码(Field2,4164553627,'Field2',解码(field3 ... 25)))