2012-05-08 79 views
0

下面的例子查詢來獲得兩個類別中的圖標..我如何結合兩個語句將一個查詢?

$fetchIcon = array(); 
$queryIcon = $db->query("SELECT * FROM icon_code WHERE icon_type = 'icon'"); 
while ($fIcon = $db->fetch_assoc($queryIcon)) { 
    $fetchIcon[] = $fIcon; 
} 

$fetchOther = array(); 
$queryOther = $db->query("SELECT * FROM icon_code WHERE icon_type = 'other'"); 
while ($fOther = $db->fetch_assoc($queryOther)) { 
    $fetchOther[] = $fOther; 
} 

然後我用foreach顯示在同一頁面的輸出中。

foreach ($fetchIcon as $Icon) { 
    echo $Icon['IconName']; // select option for Icon 
} 

foreach ($fetchOther as $Other) { 
    echo $Other['IconName']; // select option for other icon 
} 

問: 如何將二者結合起來的語句將是一個查詢?

回答

3
SELECT * 
FROM icon_code 
WHERE icon_type IN ('icon', 'other') 

然後

$fetchIcon = array(); 
$fetchOther = array(); 

while($row = mysql_fetch_assoc($result)) { 
    switch($row['icon_type']) { 
     case 'icon': 
      $fetchIcon[] = $row; 
      break; 
     case 'other': 
     default: 
      $fetchOther[] = $row; 
    } 
} 
5
SELECT * FROM icon_code 
WHERE icon_type = 'icon' 
or icon_type = 'other' 
ORDER BY icon_type 

SELECT * FROM icon_code 
WHERE icon_type in ('icon', 'other') 
ORDER BY icon_type 

order by是可選的類型來獲得訂單。

+0

加上'ORDER BY icon_type'得到完全相同的輸出。 – bfavaretto

+1

或者更普遍的說,'UNION ALL'就可以。 –

+0

@bfavaretto:很好。 –

2

我會建議使用IN功能:

$queryOther = $db->query("SELECT * FROM icon_code WHERE icon_type IN ('other', 'icon'");