[英]Mysql group_concat(id) as ids in a left join and using ids to select all columns in id group
i have a table that contains some articles with it's own ID and shared SKU key. 我有一个表格,其中包含一些带有其自己的ID和共享SKU密钥的文章。 I've tried to make the query with a left join and using group result to take all ids returned from the query. 我试图用左联接进行查询,并使用组结果获取查询返回的所有ID。
My data structure is like that: 我的数据结构是这样的:
id - name - sku - ...
1 - felix - cat
2 - tom - cat - ...
3 - sylvester - cat - ...
4 - red - pen - ...
5 - blue - pen - ...
I tried to use this query: 我尝试使用此查询:
SELECT * FROM `test`
[LEFT/RIGHT/INNER] JOIN
(
SELECT GROUP_CONCAT(DISTINCT id) AS idsgroup FROM `test` WHERE (attribute_name = 'sku') GROUP BY value_name LIMIT 0, 3
) bind
ON id IN (bind.idsgroup);
this query is wrong, it return only 1 id per group instead all ids selected from concat or in LEFT JOIN case, obviously all rows. 该查询是错误的,每个组仅返回1个ID,而不是从concat或LEFT JOIN情况下选择的所有ID,显然是所有行。
Any suggestion workaround to achieve the right result? 有任何建议解决方法可以达到正确的结果?
EDIT: 编辑:
here a fiddle with the structure: http://sqlfiddle.com/#!9/b6747a 这里的结构是一个小提琴: http : //sqlfiddle.com/#!9/b6747a
And the query i tried into: 我尝试的查询:
SELECT * FROM `view_test`
INNER JOIN
(
SELECT GROUP_CONCAT(DISTINCT entity_id) AS idsgroup FROM `view_test` WHERE (attribute_name = 'sku') GROUP BY value_name LIMIT 0, 3
) bind
ON entity_id IN (bind.idsgroup);
As this pic show, my result lost some ids, part of the group. 如这张图片所示,我的结果丢失了一些ID,属于该组。
EDIT 2: after i used FIND_IN_SET() suggested by Kickstart the result is the expected: 编辑2:在我使用了Kickstart建议的FIND_IN_SET()之后,结果是预期的:
SELECT * FROM `view_test`
INNER JOIN
(
SELECT GROUP_CONCAT(DISTINCT entity_id) AS idsgroup FROM `view_test` WHERE (attribute_name = 'sku') GROUP BY value_name LIMIT 0, 3
) bind
ON FIND_IN_SET(entity_id, bind.idsgroup);
The simple fix would appear to be to use FIND_IN_SET for the join. 简单的解决方法似乎是对联接使用FIND_IN_SET。 But this is a bit of a hack and will not be that quick. 但这是一个小技巧,并不会那么快。
SELECT *
FROM `view_test`
INNER JOIN
(
SELECT GROUP_CONCAT(DISTINCT entity_id) AS idsgroup
FROM `view_test`
WHERE (attribute_name = 'sku')
GROUP BY value_name
LIMIT 0, 3
) bind
ON FIND_IN_SET(entity_id, bind.idsgroup);
Further not sure why you have a LIMIT on the sub query, especially without an order clause. 进一步不确定,为什么在子查询上有一个LIMIT,尤其是没有order子句的情况。
Possibly better to use a sub query to just get the DISTINCT entity_id with an attribute_name of sku and join against that. 可能更好的方法是使用子查询来获得DISTINCT实体ID和sku的attribute_name并与之连接。
SELECT *
FROM `view_test`
INNER JOIN
(
SELECT DISTINCT entity_id
FROM `view_test`
WHERE (attribute_name = 'sku')
) bind
ON view_test.entity_id = bind.entity_id
Something like this? 像这样吗
SELECT t.*, group_concat(t2.id) FROM `test` t
LEFT JOIN test t2 ON t2.attribute_name = 'sku' and t.id != t2.id
group by t.id;
row, and the list of all ids that have same SKU 行,以及具有相同SKU的所有ID的列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.