我想做一個嵌套的選擇,但不同的表。這裏是我的查詢:從不同的表嵌套選擇
SELECT contact_profile.name, main_app.fk_lkp_app, main_app.id as main_id,
(
-- if the main_app.fk_lkp_app value is 1 then do this
SELECT SUM(translation_app.amount)
FROM translation_app
WHERE translation_app.fk_main_app = main_app.id
AND translation_app.status = 2
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
-- if the main_app.fk_lkp_app value is 2 then do this
SELECT SUM(interpretation_app.amount)
FROM interpretation_app
WHERE interpretation_app.fk_main_app = main_app.id
AND interpretation_app.status =2
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
-- if the main_app.fk_lkp_app value is 3 then do this
SELECT SUM(course_app.amount)
FROM course_app
WHERE course_app.fk_main_app = main_app.id
AND course_app.status =2
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
) as amount
FROM contact_profile
LEFT JOIN main_app ON main_app.fk_contact_profile = contact_profile.id
WHERE main_app.fk_lkp_app in (1,2,3)
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
GROUP BY contact_profile.name
ORDER BY amount DESC
正如你所看到的,「量」字段基於main_app.fk_lkp_app值不同的表中選擇。問題是如何做這個查詢的最佳方法?我堅持使用「main_app.fk_lkp_app」值參數部分。
我甚至使用CASE嘗試作爲建議,但它不斷給我的錯誤代碼#1064
SELECT contact_profile.name, main_app.fk_lkp_app, main_app.id as main_id,
(
CASE
WHEN main_app.fk_lkp_app = '1'
THEN (
SELECT SUM(translation_app.amount)
FROM translation_app
WHERE translation_app.fk_main_app = main_app.id
)
WHEN main_app.fk_lkp_app = '2'
THEN (
SELECT SUM(interpretation_app.amount)
FROM interpretation_app
WHERE interpretation_app.fk_main_app = main_app.id
)
WHEN main_app.fk_lkp_app = '3'
THEN (
SELECT SUM(course_app.amount)
FROM course_app
WHERE course_app.fk_main_app = main_app.id
)
ELSE 0
END CASE
) as amount
FROM contact_profile
LEFT JOIN main_app ON main_app.fk_contact_profile = contact_profile.id
WHERE main_app.fk_lkp_app in (1,2,3)
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
GROUP BY contact_profile.name
ORDER BY amount DESC
奇怪的是,如果我不使用的情況下,僅使用1從3變體中(例如:我只從translation_app表中選擇)查詢正在工作。
根據您的查詢,嵌套的選擇結果對於主要查詢的輸入而言不是必需的,因此您需要將這些嵌套的查詢轉換爲加入。 –
你可以使用'CASE'嗎? –
我該如何做到這一點?我可以加入,但不同的main_app.fk_lkp_app價值要求困擾着我。 – IkouKuhn