mysql获取不存在的结果

时间:2010-07-28 21:12:30

标签: php mysql

使用php和mysql,
我有一个表“子域名”,其中包含我的应用程序的子域名,具体取决于类别。 子域名 - id,cat_id,subdomain

某些类别具有子域名,而其他类别则没有。 对于那些没有子域名的人,我希望子域名为“www”。

现在在我的子域表中有一些值,例如:

subdomains : id, cat_id, subdomain
             1,  6,   "sales"
             2,  7,   "infos"

现在,我有一个cat_id数组,例如$ aCatIds = array(1,5,6,8);

在mysql查询结束时,我想要这样的东西:

array(
0 => (cat_id="1", subdomain="www") ,
1 => (cat_id="5", subdomain="www") ,
2 => (cat_id="6", subdomain="sales") ,
3 => (cat_id="8", subdomain="www") ,
)

只有一个mysql查询可以吗?

我使用php并尝试过这样的事情:

$stmt = "select cat_id, ifnull('www', subdomain) as subdomain
    from subdomains
    where cat_id in (". implode(',', $aCatIds) .")";

但是我只获取了设置的值(上例中为6),我不知道如何告诉mysql获取预期的数组。

1 个答案:

答案 0 :(得分:0)

要使其工作,您必须(左)加入现有数据(cat_id确实存在的地方)。例如,如果我假设cat表存在cat_id个引用,那么就是这样:

SELECT c.id as cat_id,IFNULL(s.subdomain,'www')
FROM cat c 
LEFT JOIN subdomains s
ON s.cat_id = c.id
WHERE c.id IN (1,2,3,4);
相关问题