我如何组合两个语句将是一个查询?

时间:2012-05-08 19:43:58

标签: php mysql

这里有一个示例查询来获取两种类型的图标..

$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 个答案:

答案 0 :(得分: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是可选的按类型获取订单。

答案 1 :(得分: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;
    }
}

答案 2 :(得分:2)

我建议使用IN函数:

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