2015-11-08 62 views
1
gradeid | startrange | endrange 
---------------------- 
A | 50000 | 1000000 
B | 25000 | 49999 
C | 10000 | 24999 

Employee 
id | salary 
----------- 
1 | 23000 
2 | 20000 
3 | 100000 

我想在單個查詢中獲得所有員工的成績。因爲沒有共同的字段,我可以用兩個子查詢來做到這一點。之間和加入單個查詢

select id from employee where salary 
    between (select startrange from grade where gradeid='A') 
and (select endrange from grade where gradeid='A') 

還有其他更好的SQL查詢嗎?

回答

1

您可以使用JOIN

CREATE TABLE #grades(gradeid VARCHAR(100), startrange INT, endrange INT); 

INSERT INTO #grades 
VALUES ('A', 50000, 1000000),('B', 25000, 49999),('C', 10000, 24999); 

CREATE TABLE #Employee(id INT, salary INT); 

INSERT INTO #Employee VALUES(1, 23000),(2, 20000),(3, 100000); 

SELECT e.* 
FROM #Employee e 
JOIN #grades g 
    ON e.salary BETWEEN startrange AND endrange 
WHERE g.gradeid = 'A'; 

LiveDemo

+1

這是完美的SQL查詢! –

+0

@ lad2025但與子查詢方法相比,性能不會很好 –

+0

@PreetamPurbia你比較執行計劃嗎?成績表是簡單的查找表,它是否有任何索引? – lad2025