lundi 18 janvier 2021

SQL case | If

I want to SELECT based on the user language (german or english) a value from a table. I know i can do the selection later in a PHP if/else but i want to try if i can do the selection already in my SQL query. I have seen in the documentation for SQL CASE no example or solution for my demands. I am not sure if this is possible. As i have seen only 'text' is accepted for THEN but no new SQL QUERY.

My SQL Query

$statement = $pdo->prepare("SELECT  
                              audit.id as audit_id, 
                              audit.questionaire_id, 
                              audit.assigned_auditor, 
                              audit.co_auditor_1_id, 
                              audit.co_auditor_2_id, 
                              audit.comment_positive, 
                              audit.comment_negative, 
                              audit.comment_general, 
                              audit.general_audit_status, 
                              audit.questionaire_id, 
                              audit.audit_date_start, 
                              audit.audit_date_end,
                              audit.audit_reason, 
                              audit.audited_process, 
                              audit.area,
                              departments.name,
                              departments.location,
                              suppliers.supplier_name, 
                              suppliers.supplier_country,
                              suppliers.supplier_city, 
                              users.vorname, 
                              users.nachname, 
                              users.email,    
                              questionaire.scheme,
                              questionaire.quest_name, //German translation
                              questionaire.quest_name_en // English translation
                              FROM audit 
                              LEFT JOIN suppliers
                              ON audit.supplier_id = suppliers.id 
                              LEFT JOIN users
                              ON audit.supplier_uid = users.id 
                              LEFT JOIN departments
                              ON audit.department = departments.id
                              JOIN questionaire
                              ON audit.questionaire_id = questionaire.id
                              WHERE audit.id = $id");

$result = $statement->execute(array(':id' => $_GET['id']));
$audit = $statement->fetch();

And here the section where i want to implement such a SQL CASE situation:

My Try:

... things before ...
questionaire.scheme,
CASE users.language = 'de' THEN
(SELECT quest_name FROM questionaire WHERE id = audit.questionaire_id)
ELSE (SELECT quest_name_en FROM questionaire WHERE id = audit.questionaire_id)                              
FROM audit 
... things after ...

Aucun commentaire:

Enregistrer un commentaire