4

假设我的表包含以下列

 Roll_number numeric           not null
 Subject1    varchar(40)       null
 Subject2    varchar(40)       null
 . . .
 Subject8    varchar(40)       null

我必须使用 SQL 查询在所有这些主题 1 到 8 中搜索主题。在所有这些列中搜索子字符串的最佳查询是什么,请记住其中任何一个都可以具有 NULL 值。

我写

select * 
from students_data 
where subject1="BIOLOGY" or subject2="BIOLOGY" . . . . or subject8="BIOLOGY" 

但我需要一个简单的查询,因为实际上我的表中有 20 多列

查询

select * from table1 where "BIOLOGY" in (subject1,subject2,subject3)

很有帮助,但是如果我必须只匹配该表字段中的子字符串(该主题的一部分),例如
“BIO” ,该怎么办

4

4 回答 4

5

您可以IN像这样使用谓词:

SELECT * 
FROM students_data 
WHERE 'BIOLOGY' IN (subject1, subject2, . . . , subject8);
于 2012-12-26T15:13:05.310 回答
1

这个怎么样?

SELECT * 
FROM students_data
WHERE subject1 + ' ' + subject2 + ' ' + ..... + subject8 LIKE '%BIOLOGY%';

更新 1

对于NULL值,请在下面使用。

SELECT * 
FROM students_data
WHERE ISNULL(subject1,'') + ' ' + ISNULL(subject2,'')
+ ' ' + ..... + ISNULL(subject8,'') LIKE '%BIOLOGY%';

对于使用 BIO,您可以使用LIKE '%BIO%';

于 2012-12-26T15:17:48.840 回答
1

这可能不会更快,但我相信它更清楚。

首先创建一个规范化视图(您可以以这种方式存储数据——这将是理想的)

Create View SubjectData AS
(
   SELECT Roll_number, 1 AS SubjectNumber, Subject1 AS Subject FROM TABLE1
   UNION ALL
   SELECT Roll_number, 2 AS SubjectNumber, Subject2 AS Subject FROM TABLE1
   UNION ALL
   SELECT Roll_number, 3 AS SubjectNumber, Subject3 AS Subject FROM TABLE1
   UNION ALL
   SELECT Roll_number, 4 AS SubjectNumber, Subject4 AS Subject FROM TABLE1
   UNION ALL
   SELECT Roll_number, 5 AS SubjectNumber, Subject5 AS Subject FROM TABLE1
   UNION ALL
   SELECT Roll_number, 6 AS SubjectNumber, Subject6 AS Subject FROM TABLE1
   UNION ALL
   SELECT Roll_number, 7 AS SubjectNumber, Subject7 AS Subject FROM TABLE1
   UNION ALL
   SELECT Roll_number, 8 AS SubjectNumber, Subject8 AS Subject FROM TABLE1
)

现在选择很简单:

SELECT Roll_number, SubjectNumber from SubjectData where CONTAINS(Subject,'Bio')

注意注意使用CONTAINS,无论你怎么做都应该更快。

我没有测试上述查询,他们可能有错别字。

于 2012-12-26T16:44:59.693 回答
0

在这种情况下,关于这个,

SELECT * 
FROM students_data
WHERE 
nvl(subject1,'') + ' ' + nvl(subject2,'') + ' ' + ..... + nvl(subject8,'') 
LIKE '%BIO%';

如果您的数据库不支持,请选择ifnull()decode()

于 2012-12-26T15:26:20.780 回答