SQL与INNER JOIN不同

时间:2015-02-27 00:36:53

标签: php mysql

我在选项中遇到问题如果我在查询中嵌入DISTINCT我有value= ""。如果我删除DISTINCT我有value= "1",我需要这个。

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

2 个答案:

答案 0 :(得分:0)

而不是DISTINCT,请使用GROUP BY。见下文:

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

答案 1 :(得分:0)

问题不在于DISTINCT运算符。您只在查询中选择一个名称的字段。您还需要选择ID_Category字段。有点像:

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'