Caution:
Be wary of designs that use EAV (entity, attribute, value) table designs. They tend to become very difficult to handle, for reasons of referential integrity and query complexity.
Optimize by using:
- Joins instead of sub-selects.
- Join notation.
- Explicit table aliases on all column names.
Phase 1:
SELECT e.attr_id, e.sku, a.value
FROM product_attr AS e JOIN product_attr_text AS a
ON e.attr_id = a.attr_id
WHERE a.value IN (
SELECT p.value
FROM product_attr_text AS p
JOIN eav_attr AS v ON p.attribute_id = v.attribute_id
WHERE v.attribute_code = 'similar_prod_id'
AND p.value != ''
GROUP BY value
HAVING (COUNT( value ) > 1)
)
Phase 2:
SELECT e.attr_id, e.sku, a.value
FROM product_attr AS e
JOIN product_attr_text AS a ON e.attr_id = a.attr_id
JOIN (SELECT p.value
FROM product_attr_text AS p
JOIN eav_attr AS v ON p.attribute_id = v.attribute_id
WHERE v.attribute_code = 'similar_prod_id'
AND p.value != ''
GROUP BY value
HAVING (COUNT( value ) > 1)
) AS x ON x.value = a.value