我正在构建一个查询,为我的网站上的个人资料生成预览。
查询涉及几个表,获取某些信息,即名称和COUNT()用于某个特征的统计信息,即他们有多少喜欢。
以下查询将永远执行。我看到的一个问题是我使用LEFT JOINS来获取所有数据。首先,任何人都可以帮助我如何选择我用于查询的JOIN。
除此之外,任何人都可以看到我做错了什么。什么时候执行这么长时间。
以下是查询:
SELECT u.id AS id,
u.about AS About,
CONCAT(u.fn,' ',u.ln) AS Fullname,
u.username AS Username,
i.image AS Image,
COUNT(DISTINCT a.id) AS Contacts,
COUNT(DISTINCT ul.id) AS Thumbs,
u.views AS Views,
COUNT(DISTINCT o.id) AS TrybesStarted,
COUNT(DISTINCT ti.id) AS TrybesJoined,
COUNT(DISTINCT ai.id) AS AmbitionsSupporting,
COUNT(DISTINCT am.id) AS AmbitionsCompleted,
COUNT(DISTINCT sp.id) AS Posts
FROM x_table1 u
/* PIC */
LEFT JOIN x_table2 i
ON u.id = i.user_id
/* CONTACTS */
LEFT JOIN x_table3 a
ON (u.id = a.to AND a.accepted = 1 OR u.id = a.from AND a.accepted = 1)
/* THUMBS UP */
LEFT JOIN x_table4 ul
ON (u.id = ul.profile_id)
/* TRYBES STARTED */
LEFT JOIN x_table5 o
ON (u.id = o.profile_id)
/* TRYBES JOINED */
LEFT JOIN x_table6 ti
ON (u.id = ti.to AND ti.accepted = 1)
/* AMBITIONS SUPPORTING */
LEFT JOIN x_table7 ai
ON (u.id = ai.to AND ai.accepted = 1)
/* AMBITIONS COMPLETED */
LEFT JOIN x_table8 ao
ON (u.id = ao.profile_id)
LEFT JOIN x_table9 am
ON (ao.ambition_id = am.id AND am.complete = 1)
/* POSTS */
LEFT JOIN x_table10 sp
ON (u.id = sp.profile_id)
WHERE u.id = '1234userid'
假设所有表格数据都是正确的,如果您愿意请求它,我会为您完成。
P.S。在我添加/* AMBITIONS COMPLETED */
之前,查询似乎运行正常。我认为它因为它包含一个双LEFT JOIN。
提前致谢
答案 0 :(得分:1)
经过数小时的研究,我遇到了另一种查询技术来检索以下数据:
Array
(
[ID] => useridentifier
[ABOUT] => ABOUT :)
[NAME] => Chris m
[REGISTERED] => 2013-10-21 12:54:50
[USERNAME] => Cwiggo
[VIEWS] => 3
[IMAGE] => useridentifier
[AWARDS] => 0
[TRYBANK] => 1
[USER_CONTACTS] => 6
[USER_THUMBS_UP] => 6
[TRYBES_STARTED] => 28
[TRYBES_JOINED] => 13
[USER_POSTS] => 8
[AMBITIONS_STARTED] => 40
[AMBITIONS_JOINED] => 13
[AMBITIONS_COMPLETE] => 1
[Retreival] => 0.00026202201843262
)
此数据是从我的数据库中的几个表中收集的。如您所见,查询速度非常快。无论如何,还是比挂起更好!
对查询的更改如下。我将提供一个代码段,因为它基本上重复了不同表格的代码:
SELECT u.id AS ID,
u.registered AS REGISTERED,
u.x_account_username AS USERNAME,
COALESCE(uc.cnt, 0) AS USER_CONTACTS,
COALESCE(ut.cnt, 0) AS USER_THUMBS_UP,
FROM x_user u
#IMAGES
LEFT JOIN x_user_images images ON u.id = images.user_id
#CONTACTS
LEFT JOIN
( SELECT `to`,accepted,`from`, COUNT(*) AS cnt FROM
x_allies
GROUP BY `to`) uc
ON (u.id = uc.to AND uc.accepted = 1 OR u.id = uc.from AND uc.accepted = 1)
#THUMBS UP
LEFT JOIN
( SELECT user_id, COUNT(*) AS cnt FROM
x_user_likes
GROUP BY user_id ) ut
ON u.id = ut.user_id
WHERE u.id = 'useridentifier'
我希望这个答案对试图访问,汇总和整理数据库表中统计信息的开发人员有所帮助。
感谢您发表评论
答案 1 :(得分:0)
如果在添加表x_table8和x_table9后查询变慢,那么我认为x_table9表包含大数据。尽量避免LEFT JOIN。要使用LEFT JOIN,如果你想要x_table8中的记录,即使它在x_table9表中没有相关记录,那么只使用LEFT JOIN,其他明智的JOIN可以更快地完成工作。
正如你所说,你正在使用它生成一个配置文件,那么我建议使用JOIN作为表,没有配置文件ID的数据对我来说意义不大。
如果你不能避免LEFT JOIN尝试使用临时表并在查询中使用那些速度更快的TEMP TABLES。
希望你能更快地做到这一点。