我正在尝试使用不同的表进行嵌套选择。这是我的疑问:
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
如您所见,“amount”字段是根据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
奇怪的是,如果我不使用大小写并且只使用3变量中的1个选择(例如我只从translation_app表中选择),则查询正在运行。
答案 0 :(得分:1)
您可以使用CASE
表达式检查main_app.fk_lkp的值
http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case
并根据该值执行查询。我无法测试它,但这样的事情应该起作用
SELECT contact_profile.name, main_app.fk_lkp_app, main_app.id as main_id,
CASE
WHEN main_app.fk_lkp_app = 1 THEN (/* your query here */)
WHEN main_app.fk_lkp_app = 2 THEN (/* your query here */)
WHEN main_app.fk_lkp_app = 2 THEN (/* your query here */)
ELSE 0
END AS amount ....