Querying 100k records to 5 records

时间:2015-06-25 18:58:24

标签: sql postgresql

I have a requirement in such a way that it should join two tables with more than 100k records in one table and just 5 records in another table as shown below Employee Dept Result id Name deptid deptid Name Name deptid Name 1 Jane 1 1 Science Jane 1 Science 2 Jack 2 2 Maths Dane 1 Science 3 Dane 1 3 Biology Jack 2 Maths 4 Drack 3 4 Social Drack 3 Biology 5 Drim 5 Zoology Kery 4 Social 6 Drum 5 Drum 5 Zoology 7 Krack 8 Kery 4 . . 100k Which join need to be used to get the query in an better way to perform to get the result as shown. I just want the query to join with other table from employee table only which has dept which i thought of below query but wanted to know is there any better way to do it. Select e.name,d.deptid,d.Name from (Select deptid,Name from Employee where deptid IS NOT NULL) A and dept d where A.deptid=d.deptid;

1 个答案:

答案 0 :(得分:1)

Firstly not sure why you are performing your query the way you are. Should be more like SELECT A.name, D.deptid,D.Name FROM Employee A INNER JOIN dept D ON A.deptid = D.deptid No need of the IS NOT NULL statement. If this is a ONE TIME or OCCASIONAL thing and performance is key (not a permanent query in your DB) you can leave out the join altogether and do it using CASE: SELECT A.name, A.deptid, CASE WHEN A.deptid = 1 THEN "Science" WHEN A.deptid = 2 THEN "Maths" ...[etc for the other 3 departments]... END as Name FROM Employee A If this is to be permanent and performance is key, simply try applying an INDEX on the foreign key deptid in the Employee table and use my first query above.