所以,我的初始查询就像这样:
SELECT
`surveyEntries`.`ID` AS EntryID,
`surveyEntries`.`created` AS EntryDate,
`hw_services`.`name` AS Provider,
`surveyQuestions`.`ID` AS QuestionID,
`surveyQuestions`.`label` AS Question,
`survey_meta`.`answer` AS Answer,
`surveyQuestions`.`parentID` AS ParentQuestion
FROM `survey` , `surveyQuestions` , `surveyEntries` , `survey_meta` , `hw_services`
WHERE `survey`.`ID` =2
AND `survey`.`ID` = `surveyQuestions`.`surveyID`
AND `survey`.`ID` = `surveyEntries`.`surveyID`
AND `surveyEntries`.`ID` = `survey_meta`.`entryID`
AND `hw_services`.`ID` = `surveyEntries`.`hw_serviceID`
AND `surveyQuestions`.`ID` = `survey_meta`.`questionID`
现在我已经阅读过,这是一个非常弱的冗长查询,可以进行优化。
有谁知道我怎么做到这一点?我的尝试未能提供下面相同的结果:
SELECT
`surveyEntries`.`ID` AS EntryID,
`surveyEntries`.`created` AS EntryDate,
`hw_services`.`name` AS Provider,
`surveyQuestions`.`ID` AS QuestionID,
`surveyQuestions`.`label` AS Question,
`survey_meta`.`answer` AS Answer,
`surveyQuestions`.`parentID` AS ParentQuestion
FROM `survey`
JOIN `surveyQuestions`
ON `survey`.`ID` = `surveyQuestions`.`surveyID`
JOIN `surveyEntries`
ON `survey`.`ID` = `surveyEntries`.`surveyID`
JOIN `survey_meta`
ON `survey`.`ID` = `survey_meta`.`entryID`
JOIN `hw_services`
ON `survey`.`ID` = `hw_services`.`ID`
WHERE `survey`.`ID` =2
修改::
好的,所以看了你的评论之后我就能明白为什么,愚蠢的错误。
一些连接实际上是将两个表连接在一起,而不是将它们连接到FROM表(调查)。
这是我失败的新尝试。
SELECT
`surveyEntries`.`ID` AS EntryID,
`surveyEntries`.`created` AS EntryDate,
`hw_services`.`name` AS Provider,
`surveyQuestions`.`ID` AS QuestionID,
`surveyQuestions`.`label` AS Question,
`survey_meta`.`answer` AS Answer,
`surveyQuestions`.`parentID` AS ParentQuestion
FROM `survey`
JOIN `surveyQuestions`
ON `survey`.`ID` = `surveyQuestions`.`surveyID`
JOIN `surveyEntries`
ON `survey`.`ID` = `surveyEntries`.`surveyID`
JOIN `survey_meta`
ON `surveyEntries`.`surveyID` = `survey_meta`.`entryID`
JOIN `hw_services`
ON `hw_services`.`ID` = `surveyEntries `.`hw_serviceID`
JOIN `surveyQuestions`
ON `surveyQuestions`.`ID` = `survey_meta`.`questionID`
WHERE `survey`.`ID` =2
我得到的错误是:不唯一的表/别名:'surveyQuestions'
答案 0 :(得分:1)
试试这个:
SELECT
`surveyEntries`.`ID` AS EntryID,
`surveyEntries`.`created` AS EntryDate,
`hw_services`.`name` AS Provider,
`surveyQuestions`.`ID` AS QuestionID,
`surveyQuestions`.`label` AS Question,
`survey_meta`.`answer` AS Answer,
`surveyQuestions`.`parentID` AS ParentQuestion
FROM `survey`
JOIN `surveyQuestions`
ON `survey`.`ID` = `surveyQuestions`.`surveyID`
JOIN `surveyEntries`
ON `survey`.`ID` = `surveyEntries`.`surveyID`
JOIN `survey_meta`
ON (`surveyEntries`.`ID` = `survey_meta`.`entryID` AND `surveyQuestions`.`ID` = `survey_meta`.`questionID`)
JOIN `hw_services`
ON `surveyEntries`.`hw_serviceID` = `hw_services`.`ID`
WHERE `survey`.`ID` =2