0

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

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

4 回答 4

1

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

WHERE courseID = 8946

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

于 2013-09-13T13:46:30.727 回答
0

WHERE由于您在第一个查询中没有遇到的条件,您的第二个查询中有一行。

WHERE courseID = 8946
于 2013-09-13T13:45:12.953 回答
0

你有WHERE courseID = 8946你正在将你的查询减少到一个 ID

于 2013-09-13T13:45:30.523 回答
0

我终于弄清楚了这个问题……应用程序是 Moodle,它使用一个名为 get_records_sql 的函数将查询加载到一个数组中。

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

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

像这样开始选择 -

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
于 2013-09-19T17:14:22.510 回答