我已經創建了一個存儲過程,我想添加一個替代的順序by子句。 問題是查詢失敗的「無效列名稱」aantal regels'「「無效的列名稱」,訂單上的子查詢的別名
這是我現在的查詢。
SELECT
l.lead_id,
l.afdeling_id,
l.advertentie_id,
l.naam,
l.type,
l.status,
l.herkomst,
l.aanmaakdatum,
l.klant_id,
l.overigegegevens,
af.afdelingsnaam,
(SELECT
COUNT(lead_regel_id)
FROM
Lead_regel As lr
Where
Lr.lead_id = l.lead_id And
lr.status <> 100
)
AS aantal_regels,
(SELECT
COUNT(lead_id)
FROM
Lead_unread As lu
Where
lu.lead_id = l.lead_id And
lu.user_id = @uid
)
As lead_ongelezen,
(SELECT
COUNT(lru.lead_regel_id)
FROM
Lead_regel As lr2
INNER JOIN
Lead_regel_unread As lru ON
lr2.lead_regel_id = lru.lead_regel_id
Where
lr2.lead_id = l.lead_id And
lru.user_id = @uid And
lr2.status <> 100
)
As lead_regel_ongelezen
FROM
Lead AS l
INNER JOIN
Afdeling AS af ON
l.afdeling_id = af.afdeling_id
WHERE
l.afdeling_id = @aid AND
l.status <> 100
ORDER BY
CASE WHEN @orderby = 'default' THEN l.aanmaakdatum END DESC,
CASE WHEN @orderby = 'type' THEN l.type END ASC,
CASE WHEN @orderby = 'naam' THEN l.naam END ASC,
CASE WHEN @orderby = 'reacties' THEN aantal_regels END DESC
希望有人能幫助我!
我剛剛重複了這段代碼。首先,我認爲代碼會以這種方式運行兩次。通常我使用MySQL,所以有些東西在SQL中是我的新東西。 –
這也適用,不會重複任何代碼:CASE WHEN @orderby ='reacties'THEN 12 END DESC –
@ChrisGessler - 不行,那不行。 'ORDER BY 12'確實會按照SELECT語句中第12列的順序排列。但在'CASE'語句中,'12'是一個文字值,一個標量常量,只有數字12. – MatBailie