I have two tables: data
and img
each raw from data
having 0, 1 or n images in img
table.
I want to be able to get all records from data
having more than 1 images in img
. Cannot use JOINs because I can not edit the first part of the sql query: SELECT some_defualt_columns FROM data WHERE
.
Here are my solutions:
Solution 1 Takes a while to perform but works
SELECT some_defualt_columns FROM data WHERE `id` IN
(SELECT data_id FROM
(SELECT data_id, count(*) as occ FROM
img GROUP BY data_id
HAVING occ >1)
AS tmp)
Solution 2 This should be faster than the previous (MySQL: View with Subquery in the FROM Clause Limitation) but this literally kills my MySQL server
SELECT * FROM data WHERE id IN
(SELECT data_id FROM img
GROUP BY `data_id`
HAVING count(`data_id`) > 1)
SOLUTION 3 Maybe the fastes but needs the creation of a view:
CREATE VIEW my_data_with_more_than_one_img AS
SELECT all_columns_of_data_table FROM
data JOIN img
GROUP BY img.data_id
HAVING (COUNT(img.data_id) > 1
Than execute a simple SELECT
on this:
SELECT * FROM my_data_with_more_than_one_img WHERE 1
This last solution is rather fast, but I want to know if is there any faster (or smarter) way to get this done