简体   繁体   English

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

[英]How do I combine two statement will be one query?

Here an example queries to get two type of icons.. 这里有一个示例查询以获取两种类型的图标。

$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;
}

Then I use foreach to show an ouput on the same page. 然后,我使用foreach在同一页面上显示输出。

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

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

Question : How do I combine the two statement will be one query? 问题:我如何结合两个语句将一个查询?

SELECT * FROM icon_code 
WHERE icon_type = 'icon' 
or icon_type = 'other' 
ORDER BY icon_type

or 要么

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

The order by is optional to get the order by type. order by是可选的,以按类型获取订单。

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

and then 接着

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

while($row = mysql_fetch_assoc($result)) {
    switch($row['icon_type']) {
       case 'icon':
           $fetchIcon[] = $row;
           break;
       case 'other':
       default:
           $fetchOther[] = $row;
    }
}

我建议使用IN函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM