我正在构建一个查询,它将为我的网站上的个人资料生成预览。
该查询涉及几个表,获取某些信息,即名称和 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'
假设所有表格数据都是正确的,如果您需要它,我会为您完成。
Ps 在我添加之前/* AMBITIONS COMPLETED */
,查询似乎运行良好。我认为它是因为它包含一个双 LEFT JOIN。
提前致谢