我在这里有一些关于子查询的事情,但我无法做到。
我希望带有额外字段的表中的结果显示没有来自表1中具有列值的其他表的结果。
表1:
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
}
我想在这里使用子查询。
答案 0 :(得分: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