开发者

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

开发者 https://www.devze.com 2023-03-16 12:27 出处:网络
I have the code below to query a table which retrieves arrays.The parameter $idList could have several values and may therefore produce duplicates.I am only interested in inserting one unique memalert

I have the code below to query a table which retrieves arrays. The parameter $idList could have several values and may therefore produce duplicates. I am only interested in inserting one unique 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']."','$idMember开发者_开发技巧s','$emailid')";
$insert_buffer = mysql_query($insert_query);    

Thanks very much


Simply use SELECT DISTINCT to select distinct rows.

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

You could also GROUP BY memalertid instead.

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.


$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


No need to get PHP involved. Just SELECT using GROUP BY.

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

精彩评论

暂无评论...
验证码 换一张
取 消