Sql连接同一个feild中的多个记录

时间:2016-01-15 01:45:22

标签: sql-server

我想使用下表在sql中进行连接以获取课堂详细信息:

表1:Student

+----+------+---------------+
| ID | NAME |    SUBJECT    |
+----+------+---------------+
|  1 | ABC  | Science,Maths |
|  2 | XYZ  | Geo,          |
|  3 | XCZ  | Mar,Hin       |
+----+------+---------------+

表2:ClassRoom

+----------+-----------+
| Subject  | ClassRoom |
+----------+-----------+
| Science  |         1 |
| Maths    |         2 |
| Geo      |         3 |
| Mar      |         4 |
| Hin      |         5 |
+----------+-----------+

我希望输出显示各个主题的所有教室,例如第一桌科学,数学应该采取不同的方式

select * from [Student]

left join [ClassRoom]

on [Student].SUBJECT= [ClassRoom].Subject

Expected Output:- 
+----------+------+---------------+
| ClassRoom| NAME |    SUBJECT    |
+----------+------+---------------+
|        1 | ABC  |       Science |
|        2 | ABC  |         Maths |
|        3 | XYZ  |           Geo |
|        4 | XCZ  |           Mar |
|        5 | XCZ  |           Hin |
+----------+------+---------------+

2 个答案:

答案 0 :(得分:1)

如果这两个表格字段都是LEFT JOIN,则可以LIKE String SELECT * FROM [Student] LEFT JOIN [ClassRoom] ON [Student].SUBJECT LIKE '%' + [ClassRoom].SUBJECT + '%'

scanf

答案 1 :(得分:1)

您可以使用LIKE声明

SELECT
    b.classroom, a.name, b.subject
FROM Student a
LEFT JOIN JOIN Classroom b 
    ON a.subject LIKE '%' + b.subject + '%'