select a.* from test a where 1 > (select count(*) from test where name = a.name and val > a.val )
sql語句,按name分組顯示最大的val值的欄位
問題:select count(*) from test where name = a.name and val > a.val 子查詢查出來不是一個數值嗎?那sql語句不就成了
select a.* from test a where 1 >1? 但是這個邏輯明顯是錯誤的,那正確的邏輯是什麼呢? 外層和內層是如何比較的呢?感覺智商不夠理解不了啊,,,,,
回複討論(解決方案)
當取得val最大值時,count(*) 是0 ,1>0 不是剛好滿足嗎
當 a.val 為最大值時
val > a.val 不成立,(select count(*) from test where name = a.name and val > a.val ) 返回 0 (沒有合格記錄)
1 > (select count(*) from test where name = a.name and val > a.val )
成立,該條記錄被選出
其實你已經知道了,只是沒繞過彎子來
select a.* from test a where 1 > count
count 是所有大於 a.val 的記錄數,只在不存在的時候才會有 conut 等於 0.運算式 1 > 0 成立
當 a.val 為最大值時
val > a.val 不成立,(select count(*) from test where name = a.name and val > a.val ) 返回 0 (沒有合格記錄)
1 > (select count(*) from test where name = a.name and val > a.val )
成立,該條記錄被選出
其實你已經知道了,只是沒繞過彎子來
select a.* from test a where 1 > count
count 是所有大於 a.val 的記錄數,只在不存在的時候才會有 conut 等於 0.運算式 1 > 0 成立
感謝兩位版主解答!
有些明白了,但是還有點不解,當 select a.* from test a where 2 > 0 就取了2條 我想知道這資料是怎麼得出來的呢,是跟自身進行比較得出的嗎? 因為我直接寫select a.* from test a where 1>0這個條件是可以把所有資料都取出來的。
意思就是遍曆test 表中每一條記錄,然後與自身做比較,每遍曆一條記錄,都與自身所有記錄都比較一次。
相當於php中的兩次foreach
foreach($ar as $v)
foreach($ar as $vl)
意思就是遍曆test 表中每一條記錄,然後與自身做比較,每遍曆一條記錄,都與自身所有記錄都比較一次。
相當於php中的兩次foreach
foreach($ar as $v)
foreach($ar as $vl)
我就是這麼想的,就是有點不確定,哈哈,謝謝兩位版主。