1. 程式人生 > >SQL如何Count Distinct過的資料

SQL如何Count Distinct過的資料

distinct:

<pre name="code" class="sql">SELECT distinct t1.*,t2.industryId  FROM positions t1 ,planteddetails t2, landplanted t3 where t3.landId = t1.id and t2.plantedId = t3.id
and (t1.landType like '%糧%' or t1.gatherId like '%糧%') and t2.industryId ='1'



直接count會報錯
SELECT count((distinct t1.*,t2.industryId  FROM positions t1 ,planteddetails t2, landplanted t3) where t3.landId = t1.id and t2.plantedId = t3.id
and (t1.landType like '%糧%' or t1.gatherId like '%糧%') and t2.industryId ='1'

所以我們可以換個思路
select count(*) from (SELECT distinct t1.*,t2.industryId  FROM positions t1 ,planteddetails t2, landplanted t3 where t3.landId = t1.id and t2.plantedId = t3.id
and (t1.landType like '%糧%' or t1.gatherId like '%糧%') and t2.industryId ='1') as total

直接把distinct的結果作為一張表count

這裡as total是必須的 臨時表需要名字 不然會報錯