mysql子查询只返回一行

时间:2013-09-13 13:41:04

标签: mysql sql

我有一个返回许多行的查询:

SELECT c.id AS courseID,
   c.fullname AS courseName,
   c.continuingeducationcredits AS cec,
   cc.name AS catName,
   IFNULL(ccp.name, '-No Parent Category-') AS catParent,
   ue.userid AS userID,
   CONCAT(u.firstname, ' ', u.lastname) AS name,
   ud.data AS employeeid,
   date_format(date_add('1970-01-01',interval round(c.startdate/60/60/24) DAY), '%m/%d/%Y') AS startdate,
   u.id AS uid,
   c.startdate AS cstartdate
FROM user_enrolments AS ue
INNER
    JOIN USER AS u ON ue.userid = u.id
INNER JOIN user_info_data AS ud ON (ud.fieldid = 1
                                      AND ud.userid = u.id)
INNER JOIN enrol AS e ON e.id = ue.enrolid
INNER JOIN course AS c ON c.id = e.courseid
INNER JOIN course_categories AS cc ON cc.id = c.category
LEFT
    OUTER JOIN course_categories AS ccp ON ccp.id = cc.parent
WHERE 1 = 1
  AND (cc.ID = 13
       OR ccp.ID = 13)
ORDER BY catParent,
         uid,
         cstartdate DESC

工作正常,并返回多行。但是,如果我尝试将其用作子查询:

SELECT *
FROM
  (SELECT c.id AS courseID,
          c.fullname AS courseName,
          c.continuingeducationcredits AS cec,
          cc.name AS catName,
          IFNULL(ccp.name, '-NO Parent Category-') AS catParent, ue.userid AS userID, CONCAT(u.firstname, ' ', u.lastname) AS name,
          ud.data AS employeeid,
          date_format(date_add('1970-01-01',interval round(c.startdate/60/60/24) DAY), '%m/%d/%Y') AS startdate,
          u.id AS uid,
          c.startdate AS cstartdate
   FROM user_enrolments AS ue
   INNER JOIN USER AS u ON ue.userid = u.id
   INNER JOIN user_info_data AS ud ON (ud.fieldid = 1
                                       AND ud.userid = u.id)
   INNER JOIN enrol AS e ON e.id = ue.enrolid
   INNER JOIN course AS c ON c.id = e.courseid
   INNER
    JOIN course_categories AS cc ON cc.id = c.category
   LEFT OUTER JOIN course_categories AS ccp ON ccp.id = cc.parent
   WHERE 1 = 1
     AND (cc.ID = 13
          OR ccp.ID = 13)) AS Pseudotable
WHERE courseID = 8946
ORDER BY catParent,
         uid,
         cstartdate DESC

它只会返回一行。

我做错了什么? :(

第一个查询是第二个查询的内部查询。

第一个查询获取参加某个类别课程的所有用户。第二个用于过滤该组,并仅获得参加过单一课程的用户。

4 个答案:

答案 0 :(得分:1)

公平地说......我对这个答案的评论是第一次:)

WHERE courseID = 8946

在第二个查询中。删除它,它应该工作。

答案 1 :(得分:0)

您的第二个查询中有一行是因为第一个查询中没有WHERE条件。

WHERE courseID = 8946

答案 2 :(得分:0)

您将WHERE courseID = 8946缩减为一个ID

答案 3 :(得分:0)

我终于找到了问题......应用程序是Moodle,它使用名为get_records_sql的函数将查询加载到数组中。

要求结果的第一行是唯一键。它使用该行作为数组的索引。

所以......要做到这一点:

像这样开始SELECT -

SELECT @a:=@a+1 as serial_number, c.id as courseID,

并将其添加到FROM子句 -

LEFT OUTER JOIN mdl_course_categories AS ccp ON ccp.id = cc.parent, (SELECT @a:= 0) AS a WHERE