简体   繁体   中英

Mysql select distinct ID and name

I have a MySQL table with some fields. There's a problem with 2 fields.

Fields are official_country_name_sort_field that contain unique numbers and field "official_country_name" that contain names.

I want to select official_country_name_sort_field that is unique and use it in GET method, but on site I want to show names from official_country_name .

I have this function that show id's from official_country_name_sort_field :

$sql = "select distinct official_country_name_sort_field as name from t_container,t_country where  (t_container.country_id = t_country.id) and (t_container.category = '$category') and (t_country.slug = '$slug') order by t_container.official_country_name_sort_field";

   $result = mysqli_query($link,$sql);
   if (!$result) {
         $output = 'Error fetching official country names : '.mysqli_error($link);
         include   '../templates/db/error.html.php';
         exit();
    }
    $officialCountryNames = array();
    while ($row= mysqli_fetch_array($result)) {
         $officialCountryNames []  = $row['name'];

    }

    return $officialCountryNames;

}

 <?php foreach ($officialCountryNames as $officialCountryName ) : ?> <h3> <a href="<?php echo "../currencylist?showall&country=$slug&category=$category&official_name=$officialCountryName"; ?> "><?php echo "$officialCountryName"; ?></a></h3> <?php endforeach ?> 

This show, where I have "officialCountryName" - ID's (numbers from table column "official_country_name_sort_field". How can I show names from table column "official_country_name" instead of ID's from "official_country_name_sort_field".

    $sql = "select distinct official_country_name_sort_field as code, official_country_name as name from t_container,t_country where  (t_container.country_id = t_country.id) and (t_container.category = '$category') and (t_country.slug = '$slug') order by t_container.official_country_name_sort_field";

   $result = mysqli_query($link,$sql);
   if (!$result) {
         $output = 'Error fetching official country names : '.mysqli_error($link);
         include   '../templates/db/error.html.php';
         exit();
    }
    $officialCountryNames = array();
    while ($row= mysqli_fetch_array($result)) {
         $officialCountryNames[]['name']  = $row['name'];
         $officialCountryNames[]['code']  = $row['name'];    
    }

    return $officialCountryNames;

}

Use above query and make change in while loop.

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