简体   繁体   English

嵌套的GROUP_CONCAT查询不会返回所有值

[英]Nested GROUP_CONCAT query doesn't return all values

I have a query with a few subqueries, but the strange thing is that the subqueries won't return the same values as if I execute the queries one by one manually.. At first I used 'IN' inside the queries, but no indexes were used, so I converted them to '='. 我有一个带有几个子查询的查询,但是奇怪的是,子查询不会返回与手动执行一个查询相同的值。首先,我在查询中使用了“ IN”,但没有索引被使用,所以我将它们转换为'='。 The results are the same with 'IN' or when I use the converted to '=' variation. 结果与“ IN”相同或当我使用转换为“ =”的变体时。

SELECT * 
FROM partners
WHERE id = ( 

SELECT GROUP_CONCAT( partner_id
SEPARATOR  ' OR id = ' ) 
FROM product_feeds
WHERE id = ( 

SELECT GROUP_CONCAT( DISTINCT feed_id
SEPARATOR  ' OR id = ' ) 
FROM product_data
WHERE category_id = ( 

SELECT GROUP_CONCAT( id
SEPARATOR  ' OR category_id = ' ) 
FROM product_categories
WHERE parent_id = ( 

SELECT GROUP_CONCAT( id
SEPARATOR  ' OR parent_id = ' ) 
FROM product_categories
WHERE parent_id =1 ) 

ORDER BY NULL ) 

ORDER BY NULL ) 

ORDER BY NULL ) 

When I, for example, execute the deepest nested 3 subqueries manually, I get 10,11,12,33,34,35 as the final result. 例如,当我手动执行最深的嵌套3个子查询时,最终结果为10,11,12,33,34,35。 When I execute the full 3 subqueries at once, they return 10,11,12. 当我一次执行全部3个子查询时,它们返回10、11、12。

I am missing results.. 我错过了结果。

Instead of trying to rely on GROUP_CONCAT, this is a job for INNER JOIN to get results from multiple tables where relationships exist. 而不是尝试依赖GROUP_CONCAT,这是INNER JOIN的工作,可以从存在关系的多个表中获取结果。

SELECT 
    -- Best to specify the precise fields you want here instead of *
    *

FROM partners p

INNER JOIN product_feeds pf
ON pf.partner_id = p.id

INNER JOIN product_data pd
ON pd.feed_id = pf.id

INNER JOIN product_categories pc
ON pc.id = pd.category_id

INNER JOIN product_categories pcparent
ON pcparent.id = pc.parent_id
AND pcparent.parent_id = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM