1. 程式人生 > >SQL中“有且僅有”一種狀態的寫法

SQL中“有且僅有”一種狀態的寫法

通常我們在實際的專案中總會遇到通過子級的狀態去更新父級的狀態,如下所示,有六個子級資料分別從屬於父級ID為568,591,593,且狀態各不一樣,求ID中狀態只為1的資料,簡而言之,求有且僅有狀態為1的父級節點ID.

如圖所示,要找到狀態為1且只有1的資料,即只有591滿足要求

這裡用With比較簡單,格式為With A(別名) as (Select * from 表B)

有且僅有則用到group,having

簡寫如下:

WITH IDSTATE AS

(

SELECT ID,STATE FROM IDSTATE

),

HAVEONLYSTATE AS

(

select min(ID) as ID,min(STATE) as STATE from IDSTATE
group by ID having count(ID)=1

)

SELECT *  FROM HAVEONLYSTATE