简体   繁体   中英

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 ($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.

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'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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