我有一个sql表,其中包含我需要在另一个表中加入的字符串。 首先,我从SQL表中获取了字符串:
$sql = "Select coupons.restrict_to_products From coupons Where coupons.coupon_id = 2";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$array2=implode(",", $row);
所以,如果我现在回复$array2
,它就会向我显示" 42,43,73"这就是我需要的。现在我想尝试加入另一个表格,结果如下:
$query = mysql_query("SELECT products_name FROM products_description WHERE products_id IN ($array2)");
while ($row2 = mysql_fetch_assoc($query)) {
$array3=implode(",", $row2);
echo $array3."<br>";
}
代码有效,但由于某种原因,它会向我显示每个产品名称3次,而不仅仅是一次。 echo
的结果是:
Productname 1
Productname 1
Productname 1
Productname 2
Productname 2
Productname 2
Productname 3
Productname 3
Productname 3
我错过了什么?
答案 0 :(得分:1)
使用group by
group by Productname
或者您可以尝试distinct
答案 1 :(得分:1)
优惠券可能已应用于相同的产品,因此它会返回相同产品的3
次。尝试group
id
产品SELECT products_name
FROM products_description
WHERE products_id IN ($array2)
GROUP BY products_id
,这将是唯一的。试试 -
outer apply
答案 2 :(得分:0)
使用此
$query = mysql_query("SELECT DISTINCT(products_name) FROM products_description WHERE products_id IN ($array2) ");
while ($row2 = mysql_fetch_assoc($query)) {
$array3=implode(",", $row2);
echo $array3."<br>";
}
OR
$query = mysql_query("SELECT products_name FROM products_description WHERE products_id IN ($array2) group by products_id ");
答案 3 :(得分:0)
或者如果行不重复,您可以获取与这些ID相关联的所有名称
SELECT products_id,GROUP_CONCAT(products_name) AS products_names FROM products_description WHERE products_id IN ($array) GROUP BY products_id