Sample Header Ad - 728x90

MySQL where clause with conditions based on other columns

0 votes
3 answers
105 views
I apologise for the vagueness of the title, but I couldn't find a better way. There's this MySQL table which consists of entity config mapping in a flattened structure.
CREATE TABLE entity_config (
  id int unsigned NOT NULL AUTO_INCREMENT,
  entity_id bigint NOT NULL,
  config_id bigint NOT NULL,
  config_value bigint NOT NULL,
  PRIMARY KEY (id),
  KEY entityconfig_entity_id_config_id_config_value (entity_id,config_id,config_value),
  KEY idx_config_id_config_value (config_id,config_value),
) ENGINE=InnoDB AUTO_INCREMENT=17382 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Apart from the id, there are 2 composite indexes on (entity_id, config_id, config_value) and (config_id, config_value). We have to support filter/search queries based on both config_id and config_value in the following way - Find all entity_ids that have config_id=10 and config_value=1000 and also config_id=20 and config_value=5000 The simplest way to do this is via joins
select ec1.entity_id 
from entity_config ec1 
inner join entity_config ec2 on ec1.entity_id = entity_id 
where ec1.config_id=10 
and ec1.config_value=1000 
and ec2.config_id=20 
and ec2.config_value=5000
1 join is fine but the more configs the customer wants to search, we'll have to keep adding joins and it can come to a point where we're joining the table with itself 10 times just because of 10 filters by the customer. I tried to use case when then inside the where clause like so
select entity_id from entity_config
where (
   case when config_id=10 then config_value = 1000 when config_id=20 then config_value=5000 end
)
But this is just an OR condition which gives entity_ids that have EITHER the 1st config combo or the 2nd one. Does anyone know any better or more efficient way of solving this? Thank you!
Asked by Sidharth Samant (203 rep)
Nov 14, 2024, 05:39 AM
Last activity: Nov 16, 2024, 02:16 AM