[英]MySQL Left JOIN Group_concat Performance issues
Please I need a help. 我需要帮助。 I have a query I run to fetch data from two tables, but its consuming a lot of memory it takes as much as 9 seconds to fetch about 100 records.
我有一个查询,我运行从两个表中获取数据,但它消耗了大量内存,需要9秒才能获取大约100条记录。 I may need to fetch up to 200k records at some point.
我可能需要在某个时刻获取多达200k的记录。 Please how do I optimize this query?
请问如何优化此查询?
SELECT user_id AS id, name, address, phone, city, book_title
FROM users us LEFT OUTER JOIN
(SELECT bid, GROUP_CONCAT(DISTINCT book_title SEPARATOR ' ')
AS book_title FROM user_books GROUP BY bid)bo ON bo.bid = us.user_id
On the user_books table I have multiple entries of book_titles for some users, I want to return a result that includes all the users both with a book title or not and the book_title in one column. 在user_books表上,我为一些用户提供了多个book_titles条目,我想返回一个结果,其中包括所有用户都是否有书名,而book_title在一列中。
I ran an sql explain statement for the query and got this 我为查询运行了一个sql explain语句并得到了它
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 PRIMARY us ALL NULL NULL NULL NULL 168272
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 65900
2 DERIVED user_books ALL NULL uid 4 NULL 164989
Note: I have an index for columns bid, book_title, user_id, name, address, phone, city in their respective tables. 注意:我在各自的表格中有列bid,book_title,user_id,name,address,phone,city的索引。
Please any suggestions on how to boost the performance. 请提出任何有关如何提升性能的建议。
Why you need to create derived table? 为什么需要创建派生表? why not this way:
为什么不这样:
SELECT
user_id, name, address, phone, city, GROUP_CONCAT(DISTINCT book_title SEPARATOR ' ') book_title
FROM
users us
LEFT OUTER JOIN user_books ub ON ub.bid = us.user_id
GROUP BY us.user_id
try this - much more performant than the other answer given here. 试试这个-比这里给出对方的回答更高性能。 Doing it this way prevents a lot of overhead in determining the grouping for each user_id, and you can always just add a WHERE clause to the selection from the users table if required.
这样做可以防止在确定每个user_id的分组时产生大量开销,并且如果需要,您始终可以从users表中为选择添加WHERE子句。
SELECT
*,
( SELECT GROUP_CONCAT(DISTINCT book_title SEPARATOR ' ')
FROM user_books ub
WHERE ub.bid=us.id
) AS book_title
FROM
( SELECT user_id AS id, name, address, phone, city, book_title
FROM users
) us
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.