简体   繁体   中英

PostgreSQL - Best approach for summarize data

We have data as follows in system

User data Experience Education Job Application

This data will be used across application and there are few logic also attached to these data. Just to make sure that this data are consistent across application, i thought to create View for the same and get count of these data then use this view at different places.

Now question is, as detail tables does not have relation with each other, how should i create view

  • Create different view for each table and then use group by
  • Create one view and write sub query to get these data

From performance perspective, which one is the best approach?

For eg

SELECT
  UserId,
  COUNT(*) AS ExperienceCount,
  0 AS EducationCount
FROM User
INNER JOIN Experience ON user_id = User_Id
GROUP BY 
  UserId
UNION ALL
SELECT
   UserId,
   0,
   COUNT(*)
FROM User
INNER JOIN Education ON user_id = user_id
GROUP BY 
  UserId

And then group by this to get summary of all these data in one row per user.

One way to write the query that you have specified would probably be:

SELECT UserId, SUM(ExperienceCount), SUM(EducationCount
FROM ((SELECT UserId, COUNT(*) as ExperienceCount, 0 AS EducationCount
       FROM Experience
       GROUP BY UserId
      ) UNION ALL
      (SELECT UserId, 0, COUNT(*)
       GROUP BY UserId
      )
     ) u
GROUP BY UserId;

This can also be written as a FULL JOIN , LEFT JOIN , and using correlated subqueries. Each of these can be appropriate in different circumstances, depending on your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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