有没有更好的方法来构建此SELECT语句中的嵌入式SELECT语句?

时间:2016-06-22 07:03:35

标签: mysql database

在以下MySQL代码段中,我在单个SELECT语句中使用两个嵌入式SELECT语句来从我的数据库中返回一些信息。它目前正常工作,但我不确定是否正确使用了两个嵌入式SELECT语句。

SELECT
  E.ID AS DEBATE_GROUPS_ID,
  A.TITLE AS STARTER_PACK_TITLE,
  B.TITLE AS UNITS_TITLE,
  B.UNIT_CODE AS UNITS_CODE,
  (SELECT FIRST_NAME FROM USERS WHERE ID = A.ACADEMIC_ID) AS ACADEMIC_FIRSTNAME, 
  (SELECT LAST_NAME FROM USERS WHERE ID = A.ACADEMIC_ID) AS ACADEMIC_LASTNAME,
  D.DATE_DUE AS DEBATES_DUE_DATE
FROM
  STARTER_PACKS A,
  UNITS B,
  USERS C,
  DEBATES D,
  DEBATE_GROUPS E
WHERE
  D.ID = E.DEBATE_ID AND E.STUDENT_ID = C.ID AND C.ID = 12

因此,我的问题是......

  

我在嵌入式SELECT语句中所做的是正确的,还是在提高效率或可读性方面有更好的选择?

2 个答案:

答案 0 :(得分:3)

是的,使用JOIN,虽然您的查询似乎完全错误,但您几乎没有任何加入条件!

SELECT
  E.ID AS DEBATE_GROUPS_ID,
  A.TITLE AS STARTER_PACK_TITLE,
  B.TITLE AS UNITS_TITLE,
  B.UNIT_CODE AS UNITS_CODE,
  C.FIRSTNAME AS ACADEMIC_FIRSTNAME, 
  C.LASTNAME AS ACADEMIC_LASTNAME,
  D.DATE_DUE AS DEBATES_DUE_DATE
FROM
  STARTER_PACKS A
  INNER JOIN UNITS B ON(a.Column = B.Column)
  INNER JOIN USERS C ON(C.ID = A.ACADEMIC_ID)
  INNER JOIN DEBATES D ON (SomeColumn = D.Column)
  INNER JOIN DEBATE_GROUPS E ON(D.ID = E.DEBATE_ID AND E.STUDENT_ID = C.ID)
WHERE
  C.ID = 12

请使用显式联接的正确语法,这将帮助您避免此类问题。将这些行替换为实际的列关系:

  INNER JOIN UNITS B ON(a.Column = B.Column)
  INNER JOIN DEBATES D ON (SomeColumn = D.Column)

答案 1 :(得分:0)

目前还不完全清楚这个查询的目的是什么,但是对于我所看到的,你可以替换

(SELECT FIRST_NAME FROM USERS WHERE ID = A.ACADEMIC_ID) AS ACADEMIC_FIRSTNAME

with C.FIRST_NAME AS ACADEMIC_FIRSTNAME 

and

(SELECT LAST_NAME FROM USERS WHERE ID = A.ACADEMIC_ID) AS ACADEMIC_LASTNAME 

with C.LAST_NAME AS ACADEMIC_LASTNAME

add also a where clause to join USERS and STARTER_PACKS tables `AND C.ID = A.ACADEMIC_ID

希望它有所帮助。 西蒙