简体   繁体   中英

SQL Distinct with INNER JOIN

I have problem in options If I embed DISTINCT in query I have value= "" . If I remove DISTINCT I have value= "1" and I need this.

 $query_result = mysqli_query($db, "SELECT DISTINCT C.name FROM Category AS C INNER JOIN MarketProduct AS MP ON C.Category_ID = MP.ID_Category WHERE MP.ID_Market ='$id'");

<select name="ID_Category">
<?php
while($row = mysqli_fetch_array($query_result)){   
?>

<option value="<?php echo $row['ID_Category'] ; ?>"><?php echo $row['name'] ; ?></option>


<?php
}
?>
</select>

Instead of DISTINCT , use GROUP BY . See below:

  $query_result = mysqli_query($db, "SELECT C.name FROM Category AS C INNER JOIN MarketProduct AS MP ON C.Category_ID = MP.ID_Category WHERE MP.ID_Market ='$id' GROUP BY C.name");

The problem is not the DISTINCT operator. You are only selecting one field in your query which is name. You need to select also the ID_Category field. Somehting like:

SELECT DISTINCT C.name, C.Category_ID FROM Category AS C INNER JOIN MarketProduct AS MP ON C.Category_ID = MP.ID_Category WHERE MP.ID_Market ='$id'

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