我有一个相当复杂的查询,它根据子查询对结果进行排序。这很好用。查询如下。
SELECT enrollments.*, users.*
FROM enrollments
INNER JOIN users
ON enrollments.user_id = users.id
WHERE enrollments.preview = FALSE
ORDER BY (
SELECT COUNT(progress_tracker)
FROM progress_tracker
WHERE progress_tracker.enrollment_id = enrollments.id
AND progress_tracker.completed = TRUE
)
这里我从“用户”和“注册”表中选择字段。理想情况下,我想在sql结果中再添一个字段。该字段表示ORDER BY sql的结果:
SELECT COUNT(progress_tracker)
FROM progress_tracker
WHERE progress_tracker.enrollment_id = enrollments.id
AND progress_tracker.completed = TRUE
是否可以从此查询中创建一个字段并将其附加到每行的结果中?该行的名称将恰当地称为enrollment_progress_tracker_completed_count
。如果是这样,我该怎么做?
答案 0 :(得分:2)
将子查询添加到select
,然后使用它进行排序:
SELECT e.*, u.*,
(SELECT COUNT(*)
FROM progress_tracker pt
WHERE pt.enrollment_id = e.id AND pt.completed = TRUE
) as newcol
FROM enrollments e INNER JOIN
users u
ON e.user_id = u.id
WHERE e.preview = FALSE
ORDER BY newcol;
答案 1 :(得分:2)
使用临时表
rule