2017-01-10 56 views
0

我有一個相當複雜的查詢,它根據子查詢對結果進行排序。這工作正常。查詢如下。從子查詢追加字段

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。如果是這樣,我該怎麼做?

回答

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; 
+0

哇,超爽。謝謝! – jason328

2

使用臨時表

with tempCounts as(
SELECT enrollment_id, COUNT(progress_tracker) as countValue 
FROM progress_tracker 
WHERE progress_tracker.completed = TRUE 
group by enrollment_id) 

SELECT enrollments.*, users.*,tempCounts.countValue 
FROM enrollments, users.*,tempCounts 
INNER JOIN users 
ON enrollments.user_id = users.id 
WHERE enrollments.preview = FALSE 
and enrollments.id = tempCounts.enrollment_id 
ORDER BY tempCounts.countValue