加速多个左外连接SQL查询

时间:2017-01-20 11:32:15

标签: sql postgresql query-optimization

我希望通过多个连接来加速我的SQL查询。我想要检索的内容相当于所有用户字段及其最新的相应页面,项目和俱乐部。以下查询工作正常,但需要几秒钟。我已经为所有user_id外键字段以及它所过滤的User类和College字段添加了索引,但它没有多大帮助。

我不认为我可以做简单的内部联接,因为我想让所有用户和所有表的内部联接将消除一些没有页面的用户。每个用户都有零到多页,项目和俱乐部。

SQL表

User
id
first_name
last_name
class
college

Page
id
user_id
created_at
page_text

Item
id
user_id
created_at
item_text

Club
id
user_id
created_at
club_text

当前有效,但查询速度慢

SELECT u.id,u.first_name,u.last_name,p.page_text,i.item_text,c.club_text FROM user u LEFT OUTER JOIN LATERAL \
    (SELECT page_text FROM page p2 WHERE u.id = p2.user_id ORDER BY p2.created_at DESC LIMIT 1) p ON TRUE LEFT OUTER JOIN LATERAL \
    (SELECT item_text FROM item i2 WHERE u.id = i2.user_id ORDER BY i2.created_at DESC LIMIT 1) i ON TRUE LEFT OUTER JOIN LATERAL \
    (SELECT club_text FROM club c2 WHERE u.id = c2.user_id ORDER BY c2.created_at DESC LIMIT 1) c ON TRUE \
    WHERE u.class = 'Senior' AND u.college = 'University' ORDER BY u.first_name;

2 个答案:

答案 0 :(得分:0)

我认为您可以使用适当的索引改进查询:

SELECT u.id, u.first_name ,u.last_name, p.page_text, i.item_text, c.club_text
FROM user u LEFT OUTER JOIN LATERAL
     (SELECT page_text
      FROM page p2
      WHERE u.id = p2.user_id
      ORDER BY p2.created_at DESC
      LIMIT 1
     ) p ONTRUE LEFT OUTER JOIN LATERAL
     (SELECT item_text
      FROM item i2
      WHERE u.id = i2.user_id
      ORDER BY i2.created_at DESC
      LIMIT 1
     ) i ON TRUE LEFT OUTER JOIN LATERAL
     (SELECT club_text
      FROM club c2
      WHERE u.id = c2.user_id
      ORDER BY c2.created_at DESC
      LIMIT 1
     ) c ON TRUE
WHERE u.class = 'Senior' AND u.college = 'University'
ORDER BY u.first_name;

您想要的复合(多列)索引是:

  • user(class, college, first_name, id)
  • page(user_id, created_at desc, page_text)
  • item(user_id, created_at desc, item_text)
  • club(user_id, created_at desc, club_text)

答案 1 :(得分:0)

试试它更简单:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.jquery.min.js"></script>
<select class="limitedNumbSelect2" multiple="true">
  <option value="1">Monday</option>
  <option value="2">Tuesday</option>
  <option value="3">Wednesday</option>
  <option value="4">Thursday</option>
  <option value="5">Friday</option>
  <option value="6">Saturday</option>
  <option value="6">Sunday</option>
</select>