Below is my query to get a bulk of attributes of some objects. Are there anyway to optimize and shorten it?
SELECT object_id, value, name FROM attr_text WHERE object_id IN ('43', '42', '41', '40', '39')
UNION
SELECT object_id, value, name FROM attr_varchar WHERE object_id IN ('43', '42', '41', '40', '39')
UNION
SELECT object_id, value, name FROM attr_int WHERE object_id IN ('43', '42', '41', '40', '39')
UNION
SELECT object_id, value, name FROM attr_decimal WHERE object_id IN ('43', '42', '41', '40', '39')
UNION
SELECT object_id, value, name FROM attr_datetime WHERE object_id IN ('43', '42', '41', '40', '39')
Results:
43 red color1
43 blue color2
43 small size
42 black color1
42 big size
The most obvious improvement you could make is to use a sensible schema.
Assuming that’s not an option, one thing I would suggest is changing
UNIONtoUNION ALLas you probably don’t have have multiple attributes with the same name and value. TheUNION [DISTINCT]just performs unnecessary comparisons. In any case you aren’t handling attributes with the same name and different values in your current query.