2011-08-28 42 views
0

我有一些事情在這裏做子查詢,但我無法做到。 我想從一個額外的字段的表的結果,從表1
表1顯示沒有與列值從其它表的結果:從表2中獲取行號與表1的ID

CountryId Country ISO2 ISO3 

表2:

id  noof_country state 

我必須以檢索表1 noof_country算作數區域

編輯
我的實際表一再

表1: ad_id job_country狀態刪除DAYS_LEFT

表2: CountryId國家ISO2狀態

我已經做了查詢兩個階段:

$sql_map = "select distinct c.ISO2, c.Country, a.job_country 
    from rec_countries c, rec_advert a 
    where c.status = 1 
    and DATE(a.modified_date) >= CURDATE() - INTERVAL 30 DAY 
    and c.ISO2 <> '--' 
    and c.ISO2 <> '' 
    and c.CountryId = a.job_country 
    and a.status = 1 
    and a.`delete` = 0 
    and a.days_left >0 
    "; 
$res = mysql_query($sql_map); 

while($row = mysql_fetch_array($res)){ 
    $jobs_no = count($row['job_country']); 
    $sql_job = "SELECT COUNT(job_country) AS jobs_no 
    FROM rec_advert 
    WHERE job_country = ".$row['job_country']." 
    and status = 1 
    and `delete` = 0 
    and days_left >0"; 
    $resjob=mysql_query($sql_job); 
    $rowjob = mysql_fetch_array($resjob); 

    //here jobs_no is the count of total rows 
} 

在這裏,我想要做的與子查詢。

回答

2

如果我讀的問題的權利,這應該工作:

SELECT 
    CountryId, 
    Country, 
    ISO2, 
    ISO3, 
    (
     SELECT COUNT(DISTINCT noof_country) 
     FROM table2 
     WHERE table2.id = table1.CountryId 
    ) AS noof_country_count 
FROM table1 

這不是你的問題哪一列table1立即清楚的是一個外鍵的列在table2 ...或者,如果他們甚至與此相關。如果這個查詢不適合你,請澄清你的模式。


根據您的更新信息,試試這個:

select distinct c.ISO2, c.Country, a.job_country, 
    (
     select COUNT(a2.job_country) 
     from rec_advert a2 
     where a2.job_country = a.job_country 
     and a2.status = 1 
     and a2.`delete` = 0 
     and a2.days_left >0 
    ) as jobs_no 
    from rec_countries c, rec_advert a 
    where c.status = 1 
    and DATE(a.modified_date) >= CURDATE() - INTERVAL 30 DAY 
    and c.ISO2 <> '--' 
    and c.ISO2 <> '' 
    and c.CountryId = a.job_country 
    and a.status = 1 
    and a.`delete` = 0 
    and a.days_left >0 
+0

我有一些上面編輯。你能不能請教一下。 – kamal

+0

答覆已更新。 – cdhowie

相關問題