how to delete huge mysql rows depending on not equal - mysql

the problem that its a huge amount the query would be like
DELETE FROM `members` WHERE `membership` = 'C' AND (`id` != '1' AND `id` !='2' AND ...... thousands of ids );
how I can do that ?
I did also WHERE id NOT IN ("1","2"); but also did not work
can I use loop or something like that
the IDs that I want to keep and do not delete comes from another table contains a field holds the user ID that I don't want to delete I used PHP script to help me to generate the SQL query
like
<?php
require_once("inc.php");
$realty_uids = $db->query("SELECT `uid` from `realty2` ORDER BY `uid`");
$r = $db->fetch_assoc($realty_uids);
while($r = $db->fetch_assoc($realty_uids)){
$array[] = $r['uid'];
}
$input = array_unique($array);
echo "DELETE from `members` WHERE `membership` = 'C' ";
foreach($input as $key => $value){
echo " AND `id` != '".$value."' <br>";
}
echo ";";

DELETE FROM `members` WHERE `membership` = 'C' AND NOT EXISTS (SELECT at.uid FROM `realty2` at WHERE at.uid = `members`.id);
This way worked good thanks for every one tried :)

Related

How to copy a row from one mysql table to another

Please forgive if already answered. I have looked at lots of other questions and none are helping! Basically, I want to copy a single row from one table, to another table. The problem I have struck, is the the id of the row I want to copy, is already in use, in the table I want to copy to. This is what I have at present, it works, until it strikes this problem.
INSERT INTO venues SELECT * FROM submitted_venues WHERE id='9';
It generates the error: Duplicate entry '9' for key 'id'
Is there a way to change the id number on the fly, so that it create an unused new number for the receiving table, or do I have to write a query that names and gets all of the fields for each table. Some thing like the replace statement 0 cases would be good, where 0 creates a new record!!
The 9, is just a number that I used for this example, of course it changes.
EDIT:
I have created a work around for this problem.
//get highest id number of table to copy to
$sql = "SELECT id FROM venues ORDER BY id DESC LIMIT 1";
if( $result = mysqli_query( $mysqli, $sql ) ){
$row = mysqli_fetch_array($result);
$to_id = $row[ 0 ];
//increase id
$to_id ++;
//get highest id number of table to copy from
$sql = "SELECT id FROM submitted_venues ORDER BY id DESC LIMIT 1";
if( $result = mysqli_query( $mysqli, $sql ) ){
$row = mysqli_fetch_array($result);
$from_id = $row[ 0 ];
//increase id
$from_id ++;
//get highest unused id number
$temp_id = $to_id > $from_id ? $to_id : $from_id;
//update existing record to ensure that its id number will not conflict
$sql = "UPDATE submitted_venues SET id = '$temp_id' WHERE id='$current_venue_id'";
if( $result = mysqli_query( $mysqli, $sql ) ){
$current_venue_id = $temp_id;
//copy record to normal regular venues table
$sql = "INSERT INTO venues SELECT * FROM submitted_venues WHERE id='$current_venue_id'";
if( ! $result = mysqli_query( $mysqli, $sql ) )
die("Could not copy -> " . mysqli_error($mysqli) );
//delete record from temp db table
$sql = "DELETE FROM submitted_venues WHERE id='$current_venue_id'";
if( ! $result = mysqli_query( $mysqli, $sql ) )
die("Could not delete -> " . mysqli_error($mysqli) );
}
}
}

Copy only unique entries from one table to another MySQL

I'm trying to create scheduled auto-updater for MySQL DB. The script I use is shown below. It's idea is to insert only unique products from table wp_posts to table export_copy. But this one inserts nothing.
Please help me to fix the script.
INSERT INTO `export_copy`(`name`, `link`)
SELECT p.post_title, p.guid
FROM wp_posts p
WHERE NOT EXISTS (
SELECT *
FROM export_copy, wp_posts
WHERE export_copy.id=wp_posts.ID)
Your query will never work!
Since your table's name is "wp_posts" ,it seem you want copy data from wordpress table to your own
you can handle this by php, firt you must fetch data from table and save that to an array, then export array to insert query
$link = mysqli_connect(Your_HOST , Your_User , YOUR_Pass, DB_NAME);
$q = "SELECT p.post_title, p.guid FROM wp_posts p WHERE NOT EXISTS ( SELECT * FROM export_copy, wp_posts WHERE export_copy.id=wp_posts.ID)";
$result = mysqli_query($link, $q);
$i=0;
while($row=mysqli_fetch_assoc($result))
{
$a[$i]['name'] = $row['post_title'];
$a[$i]['link'] = $row['post_title'];
$i++;
}
$q = '';
foreach($a as $a)
$q .= "('".$a['name']."','".$a['link']."'),";
$q = substr($q,0, (strlen($q)-1));
$q = "INSERT INTO `export_copy`(`name`, `link`) VALUES " . $q;
$result = mysqli_query($link, $q);

What is fastest way to update multiple columns in a table from data of another table where updating table column(s) are something?

I have these two queries which work, but they are slow as can be. What is faster, or rather fastest way of doing this?
method 1)
$query = "
UPDATE list_data_extra
INNER JOIN list_data
ON (list_data_extra.serial_no = list_data.serial_no)
SET
list_data_extra.id = list_data.id,
list_data_extra.cid = list_data.cid,
list_data_extra.first = list_data.first,
list_data_extra.last = list_data.last,
list_data_extra.tracking_number = list_data.tracking_number
WHERE list_data_extra.id='0' AND list_data_extra.cid='0'
";
method 2)
$query = "UPDATE list_data_extra
INNER JOIN list_data USING (serial_no)
SET list_data_extra.id = list_data.id,
list_data_extra.cid = list_data.cid,
list_data_extra.first = list_data.first,
list_data_extra.last = list_data.last,
list_data_extra.tracking_number = list_data.tracking_number
WHERE list_data_extra.id='0'
AND list_data_extra.cid='0'";
Not sure this other method would be faster:
method 3)
$query="SELECT * FROM list_data_extra WHERE id='0' AND cid='0'";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row=mysql_fetch_array($result)) {
$querytwo = mysql_fetch_array(mysql_query(
"SELECT id, cid, first, last, tracking_number
FROM list_data
WHERE serial_no='".$row['serial_no']."'"), MYSQL_ASSOC);
$querythree = "UPDATE list_data_extra
SET id='".$querytwo["id"]."', cid='".$querytwo["cid"]."',
first='".$querytwo["first"]."', last='".$querytwo["last"]."',
tracking_number='".$querytwo["tracking_number"]."'";
mysql_query($querythree);
}
}
Another thing i tried is this, which is building entire query then executing it all at once, which is a bit faster than above, but still slow as junk. the above is like 9 minutes per 1000 records and this here below is like 5 minutes per 1000.
method 4)
$query="SELECT * FROM list_data_extra WHERE id='0' AND cid='0'";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$id_loop = "";
$cid_loop = "";
$first_loop = "";
$last_loop = "";
$trackingnumber_loop = "";
$listids = "";
while($row=mysql_fetch_array($result)) {
$querytwo = mysql_fetch_array(mysql_query("SELECT id, cid, first, last, tracking_number FROM list_data WHERE serial_no='".$row['serial_no']."'"), MYSQL_ASSOC);
$id_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["id"]."' ";
$cid_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["cid"]."' ";
$first_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["first"]."' ";
$last_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["last"]."' ";
$trackingnumber_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["tracking_number"]."' ";
$listids .= ", ".$row['listid'];
}
$listidsb = substr($listids, 2);
$querythree = "UPDATE list_data_extra
SET
id = CASE listid
".$id_loop."
END,
cid = CASE listid
".$cid_loop."
END,
first = CASE listid
".$first_loop."
END,
last = CASE listid
".$last_loop."
END,
tracking_number = CASE listid
".$trackingnumber_loop."
END
WHERE listid IN (".$listidsb.")";
mysql_query($querythree) or die(mysql_error());
}
Is there a better and faster way to update multiple columns in many records in one table with data from another table?
CREATE TABLE list_data (
id int(11) NOT NULL AUTO_INCREMENT,
cid int(11) NOT NULL,
first varchar(255) NOT NULL,
last varchar(255) NOT NULL,
tracking_number varchar(255) NOT NULL,
serial_no varchar(9) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=555555 DEFAULT CHARSET=latin1
Unindexed JOIN and WHERE conditions can be slow, especially if they involve string data; try running these two (they make take a little time to run if the tables are large), and then trying your original query again.
ALTER TABLE list_data
ADD INDEX serial_idx (serial_no);
ALTER TABLE list_data_extra
ADD INDEX serial_idx (serial_no);

special mysql query from a joomla website

I have this context:
CREATE TABLE `atdees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`params` text NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `atdees` (`id`, `params`) VALUES
(1,'{"field282":"0","field347":"1"}'),
(2,'{"field282":"0","field347":"0"}'),
(3,'{"field282":"0"}');
I have to extract from the table the rows where :
an atdee must have the string '"field282":"0"'
an atdee has the string '"field282":"0"' but not the string '"field347":"0"'
an atdee has both string '"field282":"0"' and '"field347":"0"'
In other words I have to extract the Id 2 and 3.
Thank you.
Ps: Sorry for my english, I am not a native speaker ;)
edit: well i found my query
SELECT id
FROM atdees
WHERE
INSTR(`params`, '"field282":"0"') > 0 and
( params LIKE '%"field347":"0"%' OR
INSTR(`params`, '"field347"') = 0 )
If it's simply getting data from the database, then you can use something like this:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('id'));
$query->from($db->quoteName('#__atdees'));
$query->where($db->quoteName('params') . " = " . $db->quote('"field282":"0"') . "OR" . $db->quote('"field347":"0"'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result ) {
echo "<p>" . $result->id . "</p>";
}
Not sure if the database table is for a Joomla extensions but if so, keep it as #__atdees in your query, else change to atdees
Hope this helps

MYSQL copy row to another identical table with AUTO_INCREMENT id field

I have a movie database where movies are inserted into a table named titles with an AUTO_INCREMENT primary key named titles_id. Users can submit movies anonymously which are inserted into a separate identical table named titles_anon. After reviewing entries in titles_anon I want to insert them into titles but the id column is causing problems
I tried this:
INSERT INTO titles SELECT * FROM titles_anon WHERE
title_id='$title_id';
I either get a duplicate key error, or if the title_id does not already exist in titles it inserts OK but uses the titles_anon id instead of a new AUTO_INCREMENT value which I want.
How do I copy a row between tables when both tables have an AUTO_INCREMENT primary key?
INSERT INTO titles
(column_name1, column_name2, column_name3, column_name4,...)
SELECT title_id, col2, col3, col4,..
FROM titles_anon
WHERE title_id = '$title_id';
You define your fields in SELECT, but omit the PK and add the same fields to INSERT!
You can omit the id column completely, let mysql generate it for you. This need a little longer SQL to specify the exact columns you want to insert.
INSERT INTO titles (columns-other-than-the-primary-key)
SELECT columns-of-the-same-order FROM titles_anon
In PHP you can do something similar to:
$rs = mysql_query("select * from table_orig where RowID=$IDToCopy",$db_conn);
$row = mysql_fetch_assoc($rs);
$sql = '';
$fields = '';
foreach($row as $k => $v){
if($k == "RowID") continue;
$sql .= ",'$v'";
$fields .= ",$k";
}
$sql = "insert into table_copy (".substr($fields,1).") values (".substr($sql,1).")";
mysql_query($sql,$db_conn);
/* copy table with primary key to another table */
$table_old='colaboradores'; // your table old
$table_new='colaboradores2'; //your table new
// sql all columns withou primary key (column_key <> 'pri'
$rs=mysql_query("select column_name from INFORMATION_SCHEMA.COLUMNS
where table_name = '$table_old' and column_key <> 'pri' AND
table_schema = 'your database'");
// get all columns
$rows = mysql_fetch_assoc($rs);
$fields = '';
// mount fields in line
foreach ($rows as $k => $v) {
$fields .= ",$v[0]";
}
// remove first comma
$fields = substr($fields,1);
echo "Sintaxe for Create table in Mysql";
echo "CREATE TABLE $table_new SELECT $fields FROM $table_old ";
echo "Sintaxe for Insert from old table to new table Mysql";
echo "INSERT INTO $table_new $fields SELECT $fields FROM $table_old";