I'm trying to set a database name for a MySQL query. I've been able to get my first query to work, but the second I'm struggling to figure out where my syntax error is. I'm guessing it has something to do with the variable, but I'm stuck.
SET @db = CONCAT('SELECT client_databases.database_name
FROM client_databases
JOIN jobs ON jobs.organisation_id = client_databases.organisation_id
WHERE jobs.transaction_reference="K01-REC0000001"');
SET @q = CONCAT('SELECT receipts_lines.id, product_code, product_name, receipts_lines.is_putaway
FROM ', @db ,'.receipts
JOIN ', @db ,'.receipts_lines ON receipts_lines.receipt_id = receipts.id
WHERE reference_number="K01-REC0000001"');
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@db.