简体   繁体   English

从 MYSQL 查询中删除 Arrays 中的重复项,然后插入另一个表

[英]Remove duplicates in Arrays from MYSQL query and then insert into another table

I have the code below to query a table which retrieves arrays.我有下面的代码来查询检索 arrays 的表。 The parameter $idList could have several values and may therefore produce duplicates.参数 $idList 可能有多个值,因此可能会产生重复值。 I am only interested in inserting one unique memalertid.我只对插入一个独特的 memalertid 感兴趣。

Any advice on how to remove the duplicates would be much appreciated.任何有关如何删除重复项的建议将不胜感激。

$sql = mysql_query("SELECT  memalertid from memlist where listID IN ($idList) AND (emailyes = '1') ");
while ($info = mysql_fetch_array($sql)){
$insert_query = "insert into subsalerts (memalertid, idMembers, emailid) VALUES('".$info['memalertid']."','$idMembers','$emailid')";
$insert_buffer = mysql_query($insert_query);    

Thanks very much非常感谢

Simply use SELECT DISTINCT to select distinct rows.只需使用SELECT DISTINCT到 select 不同的行。

SELECT DISTINCT memalertid FROM memlist WHERE listID IN ($idList) AND (emailyes = '1')

You could also GROUP BY memalertid instead.您也可以改为GROUP BY memalertid

SELECT memalertid FROM memlist WHERE listID IN ($idList) AND (emailyes = '1') GROUP BY memalertid

For more information: http://dev.mysql.com/doc/refman/5.5/en/select.html .欲了解更多信息: http://dev.mysql.com/doc/refman/5.5/en/select.html

$newArray = array_unique($yourArray);

This will create a new array only with unique values;这将创建一个仅具有唯一值的新数组; excluding any duplicates.不包括任何重复项。

You can use group by clause to group the results with the same id, so that you'll get only unique ids您可以使用group by子句对具有相同 id 的结果进行分组,这样您将只获得唯一的 id

No need to get PHP involved.无需涉及 PHP。 Just SELECT using GROUP BY .只需SELECT使用GROUP BY

INSERT INTO subsalerts (memalertid, idMembers, emailid)
    SELECT memalertid, $idMembers, $emailid FROM memlist WHERE listID IN ($idList) AND emailyes = 1 GROUP BY memalertid;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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