2014-02-20 81 views
0

有一個現有的查詢梳理計數語句現有查詢

select first_name,last_name,email_address,name,captain_id,paid,p.player_num,league_id 
from stats_player p 
left join stats_player_team t on p.player_num=t.player_num 
left join stats_team s on t.team_id=s.team_num 
where season_id=2 and name is not NULL 
order by league_id,s.captain_id,name,first_name; 

我想添加這個創造結果的另一列:

select count(*) from (select * from stats_results 
where season =2 and player1_num=123 group by week)as weeks_played; 

player1_num實際上將是一個循環關閉t.player_num

問題:這可以在一個單一的聲明?

如果不是,我如何將新語句合併到下表中?

$results=mysql_query($query); 
print "<table border=1>"; 
print "<tr><td>First Name</td><td>Last Name</td><td>captain</td><td>Email?</td><td>League</td><td>Team</td><td>pay</td><td>wks played</td></tr>"; 
while ($row=mysql_fetch_assoc($results)){ 
    if($row['email_address'] != NULL){ 
    $email='y'; 
    } 
else { 
    $email='n'; 
    } 
if($row[captain_id]==$row[player_num]){ $iscapt="Captain"; } 
    else{$iscapt="";} 
$paid=$row[paid]; 
if($paid){$playpaid="<td bgcolor=#99ff33>paid</td>";} 
    else {$playpaid="<td bgcolor=#ff6633>not paid</td>";} 
printf ("<tr><td>%s</td><td> %s</td><td>%s</td><td>%s</td><td>%s</td></td><td>%s</td>%s \n</tr>", $row['first_name'],$row['last_name'],$iscapt,$email,$row['league_id'],$row['name'],$playpaid); 

} 
print "</table>"; 

回答

1

這是一個標量查詢(它最多返回1行),所以它可以作爲子查詢放在SELECT表達式列表中。
一個例子:

select first_name, 
     last_name, 
     email_address, 
     name, 
     captain_id, 
     paid, 
     p.player_num, 
     league_id, 

     ( select count(*) from (select * from stats_results 
      where season =2 and player1_num=123 group by week)as weeks_played 
     ) As column_name 

from stats_player p 
left join stats_player_team t on p.player_num=t.player_num 
left join stats_team s on t.team_id=s.team_num 
where season_id=2 and name is not NULL 
order by league_id,s.captain_id,name,first_name; 

順便說一句,這種查詢可以簡化爲:

select count(distinct week) 
from stats_results 
where season =2 and player1_num=123 
+0

感謝您的答覆,但我停留在如何將它作爲基於stats_results連接語句。 player1_num = p.player_num。 –

+0

因此,經過進一步調查,我發現適當的術語是子查詢。對MySql子查詢和COUNT的一些搜索顯示了大量的東西,希望能找到一些我可以用來學習這樣做的最佳方式。 –

+0

終於完成了這一切的工作,它是如你所描述的。我要麼試圖讓它變得更加困難,要麼我就是在矇混過關。 '(select count(distinct week) \t \t from stats_results \t \t where season = 10 and player1_num = p.player_num)as weeks' –