Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to select some rows from second table and concatenate them in comma-separated string. Query works well except one problem - It always selects all rows and ignores LIMIT.

This is part of my query which gets that string and ignores LIMIT:

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)

Full query:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
654 views
Welcome To Ask or Share your Answers For Others

1 Answer

The LIMIT clause limits the number of rows in the final result set, not the number of rows used to construct the string in the GROUP_CONCAT. Since your query returns only one row in the final result the LIMIT has no effect.

You can solve your issue by constructing a subquery with LIMIT 3, then in an outer query apply GROUP_CONCAT to the result of that subquery.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...