[英]LIMIT ignored in query with GROUP_CONCAT
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.
除了一个问题之外,查询工作正常 - 它总是选择所有行并忽略LIMIT。
This is part of my query which gets that string and ignores LIMIT: 这是我的查询的一部分,它获取该字符串并忽略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
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. LIMIT子句限制最终结果集中的行数,而不是用于在GROUP_CONCAT中构造字符串的行数。 Since your query returns only one row in the final result the LIMIT has no effect.
由于您的查询在最终结果中只返回一行,因此LIMIT无效。
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. 您可以通过使用LIMIT 3构造子查询来解决您的问题,然后在外部查询中将GROUP_CONCAT应用于该子查询的结果。
Your query is not working as you intended for the reasons @Mark Byers outlined in the other answer . 由于@Mark Byers在另一个答案中概述的原因,您的查询无法按预期工作。 You may want to try the following instead:
您可能需要尝试以下方法:
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;
An example of Mark Byers idea: Mark Byers的一个例子:
SELECT GROUP_CONCAT(id, '|', name)
FROM (
SELECT id, name
FROM users
LIMIT 3) inner
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.