Brug kun de to tabeller:
Din oprindelige forespørgsel:
SELECT subscribers.email_address,
subscribers.first_name,
subscribers.last_name,
t1.value AS Languages
FROM subscribers
LEFT JOIN (SELECT subscriber_id,
field_id,
GROUP_CONCAT(value SEPARATOR '|') AS value
FROM subscribers_multivalued
WHERE field_id=37
GROUP BY subscriber_id, field_id
) AS t1
ON subscribers.subscriber_id=t1.subscriber_id
AND t1.field_id=37
WHERE (list_id=49)
AND (state=1)
giver en forklarende plan for:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY subscribers ref FK_list_id FK_list_id 4 const 2 Using where
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 5
2 DERIVED subscribers_multivalued ALL field_fk field_fk 4 11 Using filesort
Mit forslag til at deltage:
SELECT subscribers.email_address,
subscribers.first_name,
subscribers.last_name,
GROUP_CONCAT(t1.value SEPARATOR '|') AS Languages
FROM subscribers
LEFT JOIN subscribers_multivalued t1
ON subscribers.subscriber_id=t1.subscriber_id
AND t1.field_id=37
WHERE (list_id=49)
AND (state=1)
GROUP BY subscribers.email_address,
subscribers.first_name,
subscribers.last_name
giver en forklarende plan for:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE subscribers ref FK_list_id FK_list_id 4 const 2 Using where; Using filesort
1 SIMPLE t1 ref subscriber_fk,field_fk subscriber_fk 4 test.subscribers.subscriber_id 1
Selvom jeg kun udfyldte disse to tabeller med en meget lille mængde data, tyder det på mig, at min version af forespørgslen vil køre mere effektivt mod databasen, fordi den ikke bruger den afledte tabel, som din forespørgsel genererer.
De andre tabeller kunne linkes ind i forespørgslen på stort set samme måde, og hele resultatet spoolet direkte til en csv-fil i stedet for at blive parset videre med PHP.
Dette skulle give dig et løb, der er både hurtigere og mere hukommelseseffektivt.
REDIGER
SELECT subscribers.email_address,
subscribers.first_name,
subscribers.last_name,
GROUP_CONCAT(DISTINCT t1.value SEPARATOR '|') AS Colors,
GROUP_CONCAT(DISTINCT t2.value SEPARATOR '|') AS Languages
FROM subscribers
LEFT JOIN subscribers_multivalued AS t1
ON subscribers.subscriber_id=t1.subscriber_id
AND t1.field_id=112
LEFT JOIN subscribers_multivalued AS t2
ON subscribers.subscriber_id=t2.subscriber_id
AND t2.field_id=37
WHERE (list_id=49)
GROUP BY subscribers.email_address,
subscribers.first_name,
subscribers.last_name
Bemærk brugen af DISTINCT i GROUP_CONCAT()-funktionen