SQL Query:将多个字符串类型的列连接在一起

时间:2012-12-26 15:09:55

标签: sql

假设我的表包含以下列

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

我必须使用SQL Query搜索所有这些subject1到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 个答案:

答案 0 :(得分:5)

您可以使用IN谓词,如下所示:

SELECT * 
FROM students_data 
WHERE 'BIOLOGY' IN (subject1, subject2, . . . , subject8);

答案 1 :(得分: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%';

答案 2 :(得分: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')

N.B。请注意CONTAINS的使用,但这样做会更快。

我没有测试上面的查询,他们可能有拼写错误。

答案 3 :(得分:0)

在这种情况下怎么样,

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

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