簡體   English   中英

如何在SQL Server中使用子查詢

[英]how to use subquery in sql server

詢問

 select * from tbl_emp 
    where emp_salary=(
       select  top 1 emp_salary from 
       (
          select  distinct top 3 emp_salary 
          from tbl_emp 
          order by emp_salary desc
        )
    )a
    order by emp_salary 
    or emp_salary=
    (select * from tbl_emp)

錯誤

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ')'.

您在where order by混合了whereorder by

where .....some conditions....
order by emp_salary or emp_salary=
(select * from tbl_emp)

修改您的查詢並找到適合該order by

對查詢進行布局可使其更具可讀性(縮進是您的朋友!)

有兩個問題。 首先你被命名了錯誤的子查詢與a)支架在錯誤的地點。 其次,我刪除了ORDER BY因為我不確定為什么需要它並導致錯誤。

select *
from tbl_emp 
where emp_salary = (select  top 1 emp_salary 
                    from  (select  distinct top 3 emp_salary
                           from tbl_emp 
                           order by emp_salary desc) a)
--order by emp_salary 
or emp_salary=(select * from tbl_emp)

現在重構查詢。 首先,您可以看到不需要內部子查詢

select *
from tbl_emp 
where emp_salary = (select top 1 emp_salary 
                    from tbl_emp 
                    order by emp_salary desc)
--order by emp_salary 
or emp_salary=(select * from tbl_emp)

最后值得指出的是,最后一部分( OR子句)僅在tbl_emp具有EXACTLY 1列和EXACTLY 1行的情況下才有效,換句話說,它必須返回單個值,否則將出現以下錯誤之一:


子查詢返回的值超過1。 當子查詢遵循=,!=,<,<=,>,> =或將子查詢用作表達式時,不允許這樣做。


如果未使用EXISTS引入子查詢,則只能在選擇列表中指定一個表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM