2010-07-31 14 views
9

Devo selezionare alcune righe dalla seconda tabella e concatenarle in una stringa separata da virgole. La query funziona bene tranne un problema: seleziona sempre tutte le righe e ignora LIMIT.LIMITE ignorato nella query con GROUP_CONCAT

Questa è parte della mia interrogazione che ottiene quella stringa e ignora LIMITE:

select 
    group_concat(value order by `order` asc SEPARATOR ', ') 
from slud_data 
    left join slud_types on slud_types.type_id=slud_data.type_id 
where slud_data.product_id=18 and value!='' and display=0 limit 3; 


// Result: 
+---------------------------------------------------------+ 
| group_concat(value order by `order` asc SEPARATOR ', ') | 
+---------------------------------------------------------+ 
| GA-XXXX, Bentley, CONTINENTAL FLYING SPUR, 2006   | 
+---------------------------------------------------------+ 

// Expected result: (only 3 comma-separated records, not 4) 

query full:

SELECT *,product_id id, 
    (select group_concat(value order by `order` asc SEPARATOR ', ') from slud_data left join slud_types on slud_types.type_id=slud_data.type_id where slud_data.product_id=t1.product_id and value!='' and display=0 limit 3) text 
FROM slud_products t1 
WHERE 
    now() < DATE_ADD(date,INTERVAL +ttl DAY) and activated=1 
ORDER BY t1.date desc 

risposta

10

La clausola LIMIT limita il numero di righe nel set di risultati finale, non il numero di righe utilizzate per costruire la stringa in GROUP_CONCAT. Poiché la tua query restituisce solo una riga nel risultato finale, il LIMIT non ha alcun effetto.

È possibile risolvere il problema costruendo una sottoquery con LIMIT 3, quindi in una query esterna applicare GROUP_CONCAT al risultato di tale sottoquery.

11

La query non funziona come previsto per i motivi @Mark Byers outlined in the other answer. Si consiglia di provare il seguente invece:

SELECT GROUP_CONCAT(`value` ORDER BY `order` ASC SEPARATOR ', ') 
FROM (
      SELECT `value`, `order` 
      FROM  slud_data 
      LEFT JOIN slud_types ON slud_types.type_id = slud_data.type_id 
      WHERE  slud_data.product_id = 18 AND value != '' AND display = 0 
      LIMIT  3 
     ) a; 
0

Un esempio di Mark Byers idea:

SELECT GROUP_CONCAT(id, '|', name) 
FROM (
SELECT id, name 
FROM users 
LIMIT 3) inner 
Problemi correlati