查询的最佳做法是两次选择列

时间:2012-05-19 19:20:17

标签: sql database

我有一个名为concept-relation的表,其中包含3列

(relationID, firstConceptID, secondConceptID)

我有一个名为concept的表包含2列

(ID, name)

我想在firstConceptID时获取secondConceptIDrelationID = 22的名称。

这是我提出的查询。

select * from (
      select name as source from concept where concept.ID in (
      select firstConceptID from `concept-relation` where relationID = 22
       ) 
) as e,
(
      select name as des from concept where concept.ID in (
      select secondConceptID from `concept-relation` where relationID = 22
     )
)as e

效果很好,但我想知道执行此类查询的最佳做法是什么?

1 个答案:

答案 0 :(得分:4)

需要自我加入以使其更清晰 通常 被认为是最佳做法,因为它避免了子选择/“IN”s

SELECT C1.name, C2.name
FROM Concept C1
INNER JOIN concept_Relation CR 
  ON CR.FirstConceptID = C1.ID
INNER JOIN Concept C2 
  ON CR.SecondConceptID = C2.ID
WHERE CR.RelationID = 22