Migrate data from old table to new table query - php

Need a little help creating a query that takes the topic_title, and topic_content from mb_topics, and the post_content from the mb_posts table and then inserts the mb_topics.topic_title into the forum_topics.topic_title (table.field), mb_topics.topic_content and mb_posts.post_content into the forum_posts table.
Is it possible to use a single select query?
mb tables:
CREATE TABLE IF NOT EXISTS `mb_posts` (
`id` int(11) NOT NULL,
`posted_by` bigint(20) NOT NULL DEFAULT '0',
`topic_id` int(11) NOT NULL DEFAULT '0',
`post_content` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `mb_topics` (
`id` int(11) NOT NULL,
`topic_title` varchar(75) NOT NULL DEFAULT '',
`posted_by` bigint(20) NOT NULL DEFAULT '0',
`topic_content` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
forum tables:
CREATE TABLE IF NOT EXISTS `forum_posts` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`post_content` text NOT NULL,
`post_date` datetime NOT NULL,
`post_topic` int(11) NOT NULL,
`post_by` int(11) unsigned NOT NULL
PRIMARY KEY (`post_id`),
KEY `post_topic` (`post_topic`),
KEY `post_by` (`post_by`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `forum_topics` (
`topic_id` int(11) NOT NULL AUTO_INCREMENT,
`topic_title` varchar(150) NOT NULL,
`topic_by` int(11) unsigned NOT NULL
PRIMARY KEY (`topic_id`),
KEY `topic_by` (`topic_by`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
PHP:
$get_old_data_query=mysql_query('SELECT `title`, `content` FROM `mb_topics`');
while($old_data=mysql_fetch_assoc($get_old_data_query))
{
$old_data_array[]=$old_data;
}

Something like this i guess would be ok?
<?php
$Old = mysql_query("SELECT * FROM Table WHERE Name = 'Name'");
while(mysql_fetch_array($Old)){
$Data = mysql_fetch_array($Old);
$Old1 = $Data['Name'];
mysql_query("INSERT INTO NewTable (Name) VALUES ('$Old1')");
}

This following query will fetch data from mb_posts and mb_topics tables and will insert into forum_posts table.
INSERT INTO forum_posts( post_content, post_topic, post_date, post_by )
SELECT MBP.post_content, MBT.id, NOW( ) , MBP.posted_by
FROM mb_posts AS MBP
LEFT JOIN mb_topics AS MBT ON MBP.topic_id = MBT.id
Similarly the following query will get post topics from old table (mb_topics) to new table (forum_topics).
INSERT INTO forum_topics( topic_title, topic_by)
SELECT MBT.topic_title, MBT.posted_by
FROM mb_posts AS MBP
LEFT JOIN mb_topics AS MBT ON MBP.topic_id = MBT.id

This would be 2 separate queries, because with one INSERT you can only insert into 1 table.

Related

mysql update table field from another table

i have these set of tables
CREATE TABLE `staff` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`uid` varchar(128) NOT NULL,
`name` varchar(128) NOT NULL,
`deptname` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `staff` (`id`, `uid`, `name`, `deptname`) VALUES
(1,'A100','John','Finance'),
(2,'A101','Joana','ICT'),
(3,'A103','Darrel','Maintenance'),
(4,'A104','Smith','HR');
CREATE TABLE `department` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`deptid` int(11) UNSIGNED NOT NULL DEFAULT '0',
`deptname` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `department` (`id`, `deptid`, `deptname`) VALUES
(1,'100','ICT'),
(2,'200','Finance'),
(8,'300','HR'),
(11,'400','Maintenance'),
(12,'500','Backup');
CREATE TABLE `new_staff` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`uid` varchar(128) NOT NULL,
`name` varchar(128) NOT NULL,
`deptid` int(11) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `new_staff` (`id`, `uid`, `name`, `deptid`) VALUES
(1,'A100','John','600'),
(2,'A103','Darrel','400'),
(3,'A104','Smith','300'),
(4,'A101','Joana','500'),
(5,'A105','Fran','800');
i would like to update the deptid field in the new_staff table to have the correct deptid as listed in the department table
in the new_staff table deptid are currently wrong for John and Joana
this is what i tried so far
// list all deptid exists
$result=$mysqli->query("SELECT deptid FROM department");
while ($rows=mysqli_fetch_array($result))
{$deptid[]=$rows['deptid'];}
$deptidarray = implode(', ', $deptid);
echo "<br>";
//echo "$deptidarray<br>";
$query=$mysqli->query("SELECT deptid from new_staff WHERE deptid not in ($deptidarray)");
echo "<br>";
$rowtotal = mysqli_num_rows($query);
if($rowtotal>0){
while ($row=mysqli_fetch_array($query))
{
$deptid=$row['deptid'];
// echo "$deptid,";
//$query=$mysqli->query("UPDATE new_staff set deptid='$deptid' WHERE ");
}
}
else
{
// not found
}
is this possible to do entirely in mysql?
UPDATE new_staff AS ns
JOIN staff AS s ON
ns.uid = s.uid // 1. Get same users from 2 tables
JOIN department AS d ON
s.deptname = d.deptname // 2. Get department
SET ns.deptid = d.deptid // 4. Update correct department id
WHERE ns.deptid != d.deptid; // 3. Get users where department is incorrect
Run SELECT query first before updating to verify the updates.
SELECT ns.*, d.deptid AS new_dept_id
FROM new_staff AS ns
JOIN staff AS s ON
ns.uid = s.uid
JOIN department AS d ON
s.deptname = d.deptname
WHERE ns.deptid != d.deptid;

mysql retrieve autoinc value for join insert

We have the following two tables:
CREATE TABLE IF NOT EXISTS `gp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`amount` decimal(15,2) NOT NULL,
`user` varchar(100) NOT NULL DEFAULT '',
`status` tinyint(2) NOT NULL DEFAULT '1',
`ip` varchar(20) NOT NULL DEFAULT 'N/A',
`token` varchar(100) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `gp_logs` (
`id` int(11) NOT NULL,
`log` varchar(1000) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
We JOIN them, for statistics, but we do this rarely, since the data from the 2nd table is not used too often except when we need to verify things.
Considering that we have many queries per second, how can our query be optimized to use 1 INSERT query instead of two and to insert the correct id in the 2nd table (gp_logs) that was generated by the INSERT into table gp?
Right now, we do a combination of MYSQL with PHP:
mysqli_query($con,"INSERT INTO `gp` (amount,user) VALUES ('1234','1')");
$id = mysqli_insert_id($con);
mysqli_query($con,"INSERT INTO gp_logs(id,log) VALUES ('$id','some_data')");
We want to eliminate the requirement of PHP for getting the last inserted ID and to insert both entries by running a single INSERT query (with a JOIN).

Joining three table together using an SQL statement to grab data from each table

In my database, I have 3 tables.
Jokes:
CREATE TABLE IF NOT EXISTS `jokes` (
`joke_id` int(11) NOT NULL AUTO_INCREMENT,
`joke` varchar(1024) NOT NULL,
`category_id` int(11) NOT NULL,
`vote` int(255) NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Category:
CREATE TABLE IF NOT EXISTS `category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(51) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
And finally, Comments:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`comment` text NOT NULL,
`joke_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
I need to join all three tables together to get the category name of a joke, the joke itself, and the unique comments correlating to that specific joke_id.
For the moment I can only join two tables where the joke_id = 1. This will return the comments for that joke.
This function is stored in my read controller, with the name of Joke:
public function joke($joke_id = FALSE)
{
if ($joke_id === FALSE) redirect('main'); //go to default controller
$data['results'] = $this->comments_m->getComments($joke_id, $this->uri->segment(2));
$this->load->view('template/header');
$this->load->view('template/sidebar');
$this->load->view('content/read', $data);
$this->load->view('template/footer');
}
The model (comments_m) has a function called getComments which grabs the comments correlating to joke_id = 1:
//gets the comments
function getComments (){
//joke id should grab the id of the joke which was commented on
$joke_id = 1;
$query = $this->db->query("SELECT jokes.*, comments.* FROM jokes LEFT OUTER JOIN comments ON jokes.joke_id = comments.joke_id WHERE jokes.joke_id = '$joke_id'");
return $query->result();
}
I need a SQL query in the getComments function which grabs the category name, the joke, the joke_id, comment and comment_id. How can I alter my query to return the information that I nee?
Try this query
SELECT jokes.*,category.*,comments.* from jokes
INNER JOIN category ON jokes.category_id=category.category_id
INNER JOIN comments ON jokes.joke_id=comments.joke_id
where jokes.joke_id = '$joke_id';

MySQL JOIN query more tables and return more result in one select

I would question, sorry my bad english :(
I have multiple tables
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) COLLATE utf8_slovak_ci NOT NULL,
`password` varchar(200) COLLATE utf8_slovak_ci NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`id`,`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_slovak_ci;
CREATE TABLE `user_acl` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_user` int(11) unsigned NOT NULL,
`group` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_slovak_ci;
CREATE TABLE `user_profil` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(100) COLLATE utf8_slovak_ci NOT NULL,
`fullname` varchar(100) COLLATE utf8_slovak_ci NOT NULL,
`profil` text COLLATE utf8_slovak_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_slovak_ci;
Query:
SELECT user.*, prf.*, acl.*
FROM (SELECT * FROM user LIMIT 1) AS user
LEFT JOIN user_acl AS acl ON (acl.id_user = user.id)
INNER JOIN user_profil AS prf ON (user.id = prf.id)
I have table user, user_acl, user_profil
table user and user_profil are indexed under id what is the common key
Table user_acl have id_usercommon key with table user (id) in the table but user_acl There are more rows for the table user and I need all rows from a table user_acl in one query.
You can get MySQL to combine values from multiple rows into one row with GROUP_CONCAT:
SELECT user.*, prf.*, GROUP_CONCAT(acl.id), GROUP_CONCAT(acl.group)
FROM user
LEFT JOIN user_acl AS acl ON (acl.id_user = user.id)
INNER JOIN user_profil AS prf ON (user.id = prf.id)
GROUP BY user.id;
You can't. You have to separate query, if you need more than one acl row to one user row.
[EDIT]: But if you need to to it with one query then you should use somekindof bitwise operations. http://codingrecipes.com/how-to-write-a-permission-system-using-bits-and-bitwise-operations-in-php

How do I select and match from multiple tables?

This is my table layout:
-- Table structure for table `areas`
CREATE TABLE IF NOT EXISTS `areas` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`country` varchar(20) NOT NULL,
`city` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- Table structure for table `matches`
CREATE TABLE IF NOT EXISTS `matches` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`view_id` bigint(20) unsigned NOT NULL,
`status` enum('h','n') NOT NULL,
`exp_date` date NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- Table structure for table `users`
CREATE TABLE IF NOT EXISTS `users` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`limit_age` varchar(5) NOT NULL DEFAULT '18:30',
`limit_gender` varchar(2) DEFAULT NULL,
`notifications` int(11) NOT NULL DEFAULT '0',
`name` varchar(30) NOT NULL,
`email` varchar(40) NOT NULL,
`image_big` varchar(120) NOT NULL,
`image_small` varchar(120) NOT NULL,
`crop_data` int(11) DEFAULT NULL,
`visible` tinyint(1) NOT NULL DEFAULT '0',
`age` int(11) DEFAULT NULL,
`registered_at` datetime NOT NULL,
`views` bigint(20) unsigned NOT NULL DEFAULT '0',
`hots` bigint(20) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
I will try to explain this better:
I have a given ID.
I would like to select one entry from users which is not the ID i have given
AND which user_id does not exist in matches
AND has visible = 1
AND where any country + city matches the given users country + city
Is this the correct way to do it (12 is an example of an given ID):
SELECT *
FROM users a
INNER JOIN areas ON areas.user_id = a.id
WHERE a.id NOT IN (SELECT user_id FROM matches)
AND NOT a.id = '12'
AND a.limit_age = '18:30'
AND a.visible = '1'
AND areas.country = 'sverige'
AND areas.city = 'gbg'
Sorry for the confusion :)
Ok, I'll make an attempt at this:
SELECT *
FROM users a
INNER JOIN areas ON areas.user_id = a.id
WHERE a.id NOT IN (SELECT user_id FROM matches)
AND a.visible = '1'
AND a.limit_age = '18:30'
AND a.limit_gender = 'f'
AND areas.country = ?
AND areas.city = ?;
This is SELECTing from "users", and returning a result only if that user also has an entry in the "areas" table. The first item in the WHERE clause ensures that a row will not be returned if the users.id (a.id) is found in the user_id field on the "matches" table. Next, I added checks for visible = 1, limit_age, and limit_gender as specified in his attempt. Finally, I left country and city parameterized so that they can be added as parameters in the php code. If anything that should give you a starting point.

Categories