实际上,有时我们可以避免表中的数据驱动关系,因此我们需要将它们联接起来。可以借助SELECT列表中的CASE语句来完成处理连接可能性的操作。为了理解它,我们以三个数据驱动表(即“ Student_Detail”)为例,它们具有以下数据:
mysql> Select * from student_detail; +----+---------+ | Id | Name | +----+---------+ | 1 | Harshit | | 2 | Rahul | | 3 | Aarav | +----+---------+ 3 rows in set (0.00 sec)
现在,我们有三个表,分别是“ Student_Harshit”,“ Student_Rahul”,“ Student_Aarav”,分别对学生Harshit,Rahul和Aarav进行了说明。他们有以下数据-
mysql> Select * from Student_Harshit; +----+-----------+ | Id | Remarks | +----+-----------+ | 1 | Excellent | +----+-----------+ 1 row in set (0.00 sec) mysql> Select * from Student_Rahul; +----+---------+ | Id | Remarks | +----+---------+ | 2 | Average | +----+---------+ 1 row in set (0.00 sec) mysql> Select * from Student_Aarav; +----+-------------+ | Id | Remarks | +----+-------------+ | 3 | Intelligent | +----+-------------+ 1 row in set (0.00 sec)
现在,以下查询将处理这些数据驱动的表-
mysql> Select sd.id, sd.name, CASE name WHEN 'Harshit' THEN H1.Remarks WHEN 'Rahul' THEN R1.Remarks WHEN 'Aarav' THEN A1.Remarks ELSE 'Error' END as REMARKS FROM Student_detail AS sd LEFT JOIN Student_Harshit AS H1 ON sd.id = H1.id LEFT JOIN Student_Rahul AS R1 ON sd.id = R1.id LEFT JOIN Student_Aarav AS A1 on sd.id = A1.id; +----+---------+-------------+ | id | name | REMARKS | +----+---------+-------------+ | 1 | Harshit | Excellent | | 2 | Rahul | Average | | 3 | Aarav | Intelligent | +----+---------+-------------+ 3 rows in set (0.00 sec)