0

这是加入这 4 个表的最有效方法吗?也可以只选择每个表的一些行吗?我尝试将 * 更改为列的名称,但只允许学生列表中的列。

SELECT c.classID, c.instrument, c.grade, u.ID, u.firstname, u.lastname, u.lastsongplayed, u.title
FROM studentlist s
INNER JOIN classlist c ON s.listID = c.classID
INNER JOIN (

SELECT * 
FROM users u
INNER JOIN library l ON u.lastsongplayed = l.fileID
)

u ON s.studentID = u.ID
    WHERE teacherID =3
    ORDER BY classID
    LIMIT 0 , 30

数据库结构:

CREATE TABLE IF NOT EXISTS `classlist` (
  `classID` int(11) NOT NULL AUTO_INCREMENT,
  `teacherID` int(11) NOT NULL,
  `instrument` text,
  `grade` int(11) DEFAULT NULL,
  PRIMARY KEY (`classID`),
  KEY `teacherID_2` (`teacherID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;


CREATE TABLE IF NOT EXISTS `studentlist` (
  `listID` int(11) NOT NULL,
  `studentID` int(11) NOT NULL,
  KEY `teacherID` (`studentID`),
  KEY `studentID` (`studentID`),
  KEY `listID` (`listID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE IF NOT EXISTS `users` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(60) NOT NULL,
  `password` varchar(60) NOT NULL,
  `firstname` text NOT NULL,
  `lastname` text NOT NULL,
  `sessionID` varchar(60) DEFAULT NULL,
  `lastlogin` time DEFAULT NULL,
  `registerdate` date NOT NULL,
  `isteacher` tinyint(1) DEFAULT NULL,
  `isstudent` tinyint(1) DEFAULT NULL,
  `iscomposer` tinyint(1) DEFAULT NULL,
  `lastsongplayed` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ID` (`ID`),
  UNIQUE KEY `email` (`email`,`sessionID`),
  KEY `ID_2` (`ID`),
  KEY `ID_3` (`ID`),
  KEY `lastsongplayed` (`lastsongplayed`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=63 ;

CREATE TABLE IF NOT EXISTS `library` (
  `fileID` int(11) NOT NULL AUTO_INCREMENT,
  `userID` int(11) NOT NULL,
  `uploaddate` datetime NOT NULL,
  `title` varchar(60) NOT NULL,
  `OrigComposer` varchar(60) NOT NULL,
  `composer` varchar(60) NOT NULL,
  `genre` varchar(60) DEFAULT NULL,
  `year` year(4) DEFAULT NULL,
  `arrangement` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`fileID`),
  KEY `userID` (`userID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=77 ;
4

1 回答 1

1

这是加入这 3 个表的最有效方法吗?

JOIN看起来正确,你正在加入你的钥匙。所以这应该是有效的。但是,我鼓励您分析您的查询EXPLAIN以确定其他优化。

是否可以只选择每个表的某些行?

是的。更改*为您想要的每个表中的列。我鼓励您使用原始表明确地为它们添加前缀。根据您选择的列,这也可以使您的查询更高效。

SELECT studentlist.studentID, users.email FROM ...
于 2012-12-02T16:49:32.340 回答