For the last few days, I have been working to write a MySQL query to extract a result. Basically, I have to join two tables log
and conditions
table based on any column of the log
table from the trigger_param_value
column. Here the column name of log
table is present in the trigger_param_name
column of the condition
table.
I have already write a SQL query.
select al.* from log as al
inner join conditions as hc on hc.action=al.action
and al.<hc.trigger_param_name> = hc.trigger_param_value
where al.date_time >= DATE_SUB(CURRENT_DATE, INTERVAL 2 DAY)
AND al.date_time < CURRENT_DATE and customer_id is not null
group by al.customer_id;
The problem is occurring for the second condition of the inner joining al.<hc.trigger_param_name>= hc.trigger_param_value
. <hc.trigger_param_name>
contains the column name of the column name of the log table.
Note: The trigger_param_name
column contains different different column name based on row.
How can I dynamically set the column name?
2
Answers
You can’t. You will need to write out the separate join criteria for each of the columns:
This query should lead to a 1055 error, as
customer_id
is not a unique key within thelog
table. Without knowing the structure of the tables and expected outcome, it is not possible to suggest how this should be fixed.Please read MySQL Handling of GROUP BY for more details on the importance of
ONLY_FULL_GROUP_BY
and writing deterministic queries.You cannot dynamically set the column name, but there are other ways to achieve what you want. One i can suggest is using case statement.
I should mention while you cannot dynamically set the column name as filter, you can make entire query dynamic for your reference. But for your case, query above i provided should be enough.