2017-01-16 46 views
0

我正在使用MySQL。我有兩張桌子,我正在加入。我需要使用count(a.parent_id)作爲countcolumn,所以這個列將被添加到我用select創建的表中。我想知道每個「parent_id」出現的數字,但要根據下面的查詢查看包含該列的所有表。該 問題是,它僅返回1個記錄,類似有同樣的它計算所有父..MYSQL與計數或有計數問題

select count(parent_id) as count_column 
    , a.parent_id 
    , b.job_id 
    , a.status as parent 
    , b.status as subparent 
    , b.description 
from jobs a 
inner join jobs_steps b 
    on a.id=b.job_id 
where name='XXX' 
    and a.status='FAILED' 
order by a.parent_id desc 

如果我刪除它返回78條記錄

select a.parent_id 
    , b.job_id 
    , a.status as parent 
    , b.status as subparent 
    , b.description 
from jobs a 
inner join jobs_steps b 
    on a.id=b.job_id 
where name='XXX' 
    and a.status='FAILED' 
order by a.parent_id desc 

開始計數父ID我希望有78個新記錄欄記錄每個parent_id出現的編號。

+0

即使mySQL不需要它,(由於[擴展組] by(https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html)子句)在使用諸如count,max,avg,min之類的聚合函數時,所有不屬於聚合的部分的列應包含在「group by」子句中。否則,引擎可以自由選擇未聚合列中的單個值並返回其值。如果所有的值都是相同的,但是如果值不同,那麼定義組可能會產生更接近所需的結果。這解釋了爲什麼你只獲得1條記錄。 – xQbert

+0

我想你想'GROUP BY a.parent_id ,b.job_id ,a.status父 ,b.status爲subparent ,b.description'不僅僅是a.parent_ID – xQbert

回答

1

如果你想按照父母身份分組你的結果,你應該使用GROUP BY,但是這不會返回給你78個記錄,因爲這些記錄不是每個父母身份組的記錄,這將返回每個父母身份記錄的記錄。我希望這有助於

select count(a.parent_id) as count_column 
    , a.parent_id 
    , b.job_id 
    , a.status as parent 
    , b.status as subparent 
    , b.description 
from jobs a 
inner join jobs_steps b 
    on a.id=b.job_id 
where name='XXX' 
    and a.status='FAILED' 
group by a.parent_id 
order by a.parent_id desc 
+1

'集團by'一定要來在SQL中的'order by'之前。 – xQbert

+0

@xQbert更新,我忘了:)謝謝! – Roljhon

+0

小組對我來說不好。任何其他建議? – OhadS

0

假設你的步驟,在每個作業數之後是(爲每個工作細節重複值)

通常我會使用一個窗口的功能,但在MySQL不支持,使用查詢計數PARENT_ID的每個作業的號碼,然後加入回來...

select C.JobSteps as count_column 
    , a.parent_id 
    , b.job_id 
    , a.status as parent 
    , b.status as subparent 
    , b.description 
from jobs a 
inner join jobs_steps b 
    on a.id=b.job_id 
LEFT JOIN (Select count(parent_ID) as JobSteps, job_ID 
      from Job_Steps 
      Group by Job_ID) C 
on c.Job_ID = B.Job_ID 
where name='XXX' 
    and a.status='FAILED' 
order by a.parent_id desc 

這對我來說似乎不是用在選擇相關的查詢方案快。

select a.parent_id 
    , b.job_id 
    , a.status as parent 
    , b.status as subparent 
    , b.description 
    , (Select count(JS.parent_ID) as JobSteps, JS.job_ID 
      from Job_Steps JS 
      where a.Id = JS.Job_ID 
      Group by Job_ID) C as count_column 
from jobs a 
inner join jobs_steps b 
    on a.id=b.job_id 
where name='XXX' 
    and a.status='FAILED' 
order by a.parent_id desc