2012-11-20 81 views
0

我有一個查詢,看起來像這樣:MySQL的計數行加入

Select x.date, x.id, x.phone, 
    x.product, xy.policy,xy.date 
from (y left join z 
      on y.customer_id=z.customer_id) 
    left join x 
     on x.id=z.id 
    left join xy 
     on xy.id=x.id 
where x.date > '2000-01-01' 
    and y.detail =foo 
    and xy.policy like 'foo_____' 
    and xy.policy_type = foo; 

我怎麼能算的行這個回報率是多少?

我試過使用SQL_CALC_FOUND_ROWS,但我不能完全適合這個查詢。

任何幫助將不勝感激。

謝謝, Stefan。

+0

可以概括查詢和周圍添加一些代碼的標籤嗎? – Ruben

+0

是否要爲結果的總行添加另一列?例如'ID,ColA,TotalResult','1,1,4','1,2,4','1,3,4','1,4,4'? –

+0

不,謝謝,我只想得到這個回報的計數。基本上,如果我可以包裹一個計數(),我會完成。 – StefanHanotin

回答

0

你可以寫:

SELECT COUNT(1) 
    FROM y 
    JOIN z 
    ON y.customer_id = z.customer_id 
    JOIN x 
    ON x.id = z.id 
    JOIN xy 
    ON xy.id = x.id 
WHERE x.date > '2000-01-01' 
    AND y.detail = foo 
    AND xy.policy LIKE 'foo_____' 
    AND xy.policy_type = foo 
; 

(注我冒昧地將LEFT JOIN改爲JOIN,因爲WHERE條款無論如何阻止它們實際上起到LEFT JOIN的作用。如果你想真正LEFT JOIN S,你可以移動從WHERE子句條件爲ON條款:

SELECT COUNT(1) 
    FROM y 
    LEFT 
    JOIN z 
    ON z.customer_id = y.customer_id 
    LEFT 
    JOIN x 
    ON x.id = z.id 
    AND x.date > '2000-01-01' 
    LEFT 
    JOIN xy 
    ON xy.id = x.id 
    AND xy.policy LIKE 'foo_____' 
    AND xy.policy_type = foo 
WHERE y.detail = foo 
; 

+0

您的查詢不會返回正確的行數。 – StefanHanotin

+0

@StefanHanotin:哪一個? – ruakh

+0

最下面一個不正確 – StefanHanotin

1

最簡單的就是隻需添加一個子查詢...

Select x.date, x.id, x.phone, 
    x.product, xy.policy,xy.date, 
    (Select Count(*) 
    From (y left join z on y.customer_id=z.customer_id) 
     left join x on x.id=z.id 
     left join xy on xy.id=x.id 
    where x.date > '2000-01-01' 
     and y.detail =foo 
     and xy.policy like 'foo_____' 
     and xy.policy_type = foo) RecordCount 
from (y left join z 
      on y.customer_id=z.customer_id) 
    left join x 
     on x.id=z.id 
    left join xy 
     on xy.id=x.id 
where x.date > '2000-01-01' 
    and y.detail =foo 
    and xy.policy like 'foo_____' 
    and xy.policy_type = foo; 

如果你想要的是計數,那麼:

Select Count(*) 
From (y left join z on y.customer_id=z.customer_id) 
    left join x on x.id=z.id 
    left join xy on xy.id=x.id 
where x.date > '2000-01-01' 
    and y.detail =foo 
    and xy.policy like 'foo_____' 
    and xy.policy_type = foo 
+0

嗨查爾斯,你的查詢返回正確的數量,但我想要的只是計數。我不想要桌子。我只想要一個數字來計算行數。 – StefanHanotin

+0

然後,只需使用內部子查詢..我編輯,以表明這一點。 –