Ich versuche, eine verschachtelte Auswahl aber mit verschiedenen Tabellen zu tun. Hier ist meine Frage:Verschachtelte Auswahl aus verschiedenen Tabellen
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
Wie Sie sehen können, das Feld „Betrag“ aus verschiedenen Tabellen basierend auf main_app.fk_lkp_app Wert ausgewählt wird. Das Problem besteht darin, wie diese Abfrage am besten durchgeführt werden kann. Ich stecke mit dem Wertparameter-Teil "main_app.fk_lkp_app" fest.
Ich habe sogar versucht CASE mit, wie vorgeschlagen, aber es hält mich Fehlercode # 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
Die seltsame Sache zu geben, wenn ich von der 3-Variante nicht verwenden Fall verwenden und nur 1 wählen (zum Beispiel Ich wähle nur aus der Tabelle translation_app) die Abfrage funktioniert.
Gemäß Ihrer Abfrage ist das geschachtelte Auswahlergebnis für die Eingabe für die Hauptabfrage nicht erforderlich. Daher müssen Sie diese verschachtelten Abfragen in Join verschieben. –
Kannst du 'CASE' einfach benutzen? –
Wie erreiche ich das? Ich kann mich anschließen, aber die andere Main_app.fk_lkp_app Wertanforderung steckt meinen Kopf fest. – IkouKuhn