2010-07-28 72 views
0

使用php和mysql,
我有一個表「子域」,它包含我的應用程序的子域,具體取決於類別。 subdomains - id,cat_id,subdomainmysql獲取不存在的結果

某些類別具有子域名,而其他類別沒有。 對於那些沒有子域名的人,我希望子域名是'www'。

現在在我的子域表有幾個值,例如:

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

現在,我有CAT_ID的陣列,例如$ aCatIds =陣列(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得到預期陣列。

+0

什麼是‘沒有子域’是什麼意思? – 2010-07-28 21:15:45

+0

如果類別有一個與之關聯的特殊子域,則將其寫入數據庫,否則不會寫入(它不存在於數據庫中) – ling 2010-07-28 21:44:24

回答

0

爲了完成這項工作,您必須(左側)加入現有數據(其中cat_id確實存在)。舉例來說,如果我承擔了cat表中存在該cat_id引用,「T會如此:在該行的實際數據方面

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); 
+0

我試過 SELECT c.id as cat_id,IFNULL(s。子域,'www') FROM cat c LEFT JOIN子域名s ON s.cat_id = c.id WHERE c.id IN(1,5,6,8); 但我得到的只是「cat_id = 6」行。 – ling 2010-07-28 21:48:41

+1

然後1,5&8也不在'cat'表中,它們在哪個表中存在?它們是否存在於任何表格中? – Wrikken 2010-07-28 22:01:22

+0

1,5,6和8都在貓表中。 cat和subdomains表均屬於innoDB類型。 但1,5和8不在結果集中,我只得到1條單行, ,cat_id = 6和subdomain ='銷售' – ling 2010-07-29 04:44:47