在 MySQL 中,如何通过连接维护数据驱动的表关系?
事实上,有时我们可以避免表中数据驱动的关系,需要将它们连接起来。借助 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)
广告