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;
Related
When I trying to run the code, this error shows up
Cannot add or update a child row: a foreign key constraint fails
(hotel_info.results, CONSTRAINT results_ibfk_5 FOREIGN KEY
(CustomerID) REFERENCES customer (CustomerID) ON DELETE CASCADE
ON UPDATE CASCADE)
Here is the code
$result = mysql_query("select customer.CustomerID from customer inner join results on customer.CustomerID = results.CustomerID where customer.Username = '".$aid."'");
if (false === $result)
{
echo mysql_error();
}
if (isset($_POST["submitbtn"]))
{
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$checkin = $_POST["CheckIn"];
$checkout = $_POST["CheckOut"];
$unit = $_POST["unit"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
if($checkin>$checkout)
{
?>
<script type="text/javascript">
alert("End Date must greater than Start Date.");
</script>
<?php
}
else
{
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$result')");
if (false === $query)
{
echo mysql_error();
}
echo "Reservation form has been submitted!<br>
<a href=view.php>view all</a>";
}
}
Here is the sql
CREATE TABLE IF NOT EXISTS `results` (
`BookID` int(10) NOT NULL AUTO_INCREMENT,
`LP` varchar(50) DEFAULT NULL,
`budget` varchar(50) DEFAULT NULL,
`CheckIn` varchar(50) DEFAULT NULL,
`CheckOut` varchar(50) DEFAULT NULL,
`unit` int(50) DEFAULT NULL,
`SmokeP` varchar(50) DEFAULT NULL,
`sp_req` varchar(255) DEFAULT NULL,
`CustomerID` int(10) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `Username` (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;
CREATE TABLE IF NOT EXISTS `customer` (
`CustomerID` int(10) NOT NULL AUTO_INCREMENT,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`ContactNo` int(10) NOT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I've already stuck for two days because of this error, please help.
from the error it is clear that foreign key constraint fails. Please check your customer table which must have CustomerID that you are trying to insert in results table insert query i.e. check value of $id. have you assigned any value for $id
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$id')");
In above query value for $id not set so first assign value to that.
I have a Search page where users can search based on certain criteria. I cannot get the query right to display only one of the desired objects. It is displaying multiple entries for specified criteria. Here is our database setup:
CREATE TABLE Class
(
cid int NOT NULL,
classNum int,
classDept varchar(20),
PRIMARY KEY (cid)
);
CREATE TABLE Book
(
bid int NOT NULL,
cid int NOT NULL,
title varchar(20) NOT NULL,
author varchar(20) NOT NULL,
isbn varchar(13),
price decimal(5,2) NOT NULL,
PRIMARY KEY (bid),
FOREIGN KEY (cid) REFERENCES Class (cid)
);
CREATE TABLE Contact
(
contactID int NOT NULL,
fname varchar(20),
lname varchar(20),
contactInfo varchar(90) NOT NULL,
PRIMARY KEY (contactID)
);
CREATE TABLE Post
(
pid int NOT NULL,
contactID int NOT NULL,
bid int NOT NULL,
postDate date,
PRIMARY KEY (pid),
FOREIGN KEY (contactID) references Contact(contactID),
FOREIGN KEY (bid) references Book(bid)
);
Here is the php code we are using to try to query based on criteria the user has entered.
$author = $_POST["author"];
$title = $_POST["title"];
$classNum = $_POST["number"];
$classDept = $_POST["department"];
$isbn = $_POST["isbn"];
$query = "SELECT title, author, isbn, price, classNum, classDept, contactInfo
FROM Book, Class, Contact, Post
WHERE Book.cid=Class.cid AND Contact.contactID=Post.ContactID and Book.bid=Post.bid AND Book.author='$author' OR Book.title='$title' ";
$stid = oci_parse($conn,$query);
oci_execute($stid,OCI_DEFAULT);
What are we doing wrong? How can we get the proper search results to display?
I'm not entirely sure that the join syntax in Oracle is the same as mysql ( which is what this was built and tested in ) but given the dummy data and minor modifications to some tables ( adding auto_increment to primary keys ) it returns the expected two rows that match the params.
create table if not exists `book` (
`bid` int(11) not null auto_increment,
`cid` int(11) not null,
`title` varchar(64) not null,
`author` varchar(20) not null,
`isbn` varchar(13) default null,
`price` decimal(5,2) not null,
primary key (`bid`),
key `cid` (`cid`),
constraint `book_ibfk_1` foreign key (`cid`) references `class` (`cid`)
) engine=innodb auto_increment=5 default charset=utf8;
insert into `book` (`bid`, `cid`, `title`, `author`, `isbn`, `price`) values
(1, 1, 'deranged dahlias', 'gertrude geikel', '1234-cdbs-9d', 250.00),
(2, 1, 'mental magnolias', 'gertrude geikel', '4234-cdfg-9f', 225.00),
(3, 1, 'raging roses', 'gertrude geikel', '4389-fkpl-8d', 120.25),
(4, 3, 'peaceful petunias', 'alice cooper', '9043-dflk-01', 500.25);
create table if not exists `class` (
`cid` int(11) not null auto_increment,
`classnum` int(11) default null,
`classdept` varchar(20) default null,
primary key (`cid`)
) engine=innodb auto_increment=4 default charset=utf8;
insert into `class` (`cid`, `classnum`, `classdept`) values
(1, 404, 'fookology'),
(2, 403, 'forbidden fruits'),
(3, 200, 'goodness');
create table if not exists `contact` (
`contactid` int(11) not null auto_increment,
`fname` varchar(20) default null,
`lname` varchar(20) default null,
`contactinfo` varchar(90) not null,
primary key (`contactid`)
) engine=innodb auto_increment=3 default charset=utf8;
insert into `contact` (`contactid`, `fname`, `lname`, `contactinfo`) values
(1, 'joe', 'bloggs', 'chief headbanger'),
(2, 'fred', 'flintstone', 'potatopeeler');
create table if not exists `post` (
`pid` int(11) unsigned not null auto_increment,
`contactid` int(11) not null,
`bid` int(11) not null,
`postdate` date default null,
primary key (`pid`),
key `contactid` (`contactid`),
key `bid` (`bid`),
constraint `post_ibfk_1` foreign key (`contactid`) references `contact` (`contactid`),
constraint `post_ibfk_2` foreign key (`bid`) references `book` (`bid`)
) engine=innodb auto_increment=3 default charset=utf8;
insert into `post` (`pid`, `contactid`, `bid`, `postdate`) values
(1, 1, 1, '2015-12-02'),
(2, 2, 4, '2015-12-02');
Query run in mysql gui - not sure if the join syntax is the same in oracle .
set #_author='alice cooper';
set #_title='mental magnolias';
select * from `book` b
left outer join `class` c on c.`cid`=b.`cid`
left outer join `post` p on p.`bid`=b.`bid`
left outer join `contact` ct on ct.`contactID`=p.`contactID`
where b.`title`=#_title or b.`author`=#_author;
Or, for php
$author=$_POST['author'];
$title=$_POST['title'];
$sql="select * from `book` b
left outer join `class` c on c.`cid`=b.`cid`
left outer join `post` p on p.`bid`=b.`bid`
left outer join `contact` ct on ct.`contactID`=p.`contactID`
where b.`title`='{$title}' or b.`author`='{$author}';";
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.
I am developing a cooking recipe-website and i want to create a recipe finder based on the used incredients.
My current finder only works with 3 ingredients right.
The Finder should return the right recipe(s) based on the used incredients (should work with 1-n*)
My Tables:
CREATE TABLE IF NOT EXISTS `INGREDIENTS` (
`ingredients_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `INGREDIENTS_POS` (
`ingredients_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`ingredients_id` int(11) NOT NULL,
`ingredients_unit` varchar(20) NOT NULL,
PRIMARY KEY (`ingredients_pos_id`),
KEY `ingredients_detail_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `RECIPES` (
`recipes_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) COLLATE utf8_bin NOT NULL,
`text` varchar(2000) COLLATE utf8_bin NOT NULL,
`count_persons` int(11) NOT NULL,
`duration` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`date` datetime NOT NULL,
`accepted` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`recipes_id`),
KEY `recipes_user_fk` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=88 ;
CREATE TABLE IF NOT EXISTS `RECIPES_POS` (
`recipes_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`recipes_id` int(11) NOT NULL,
`ingredients_id` int(11) NOT NULL,
`ingredients_value` int(11) NOT NULL,
PRIMARY KEY (`recipes_pos_id`),
KEY `recipe_pos_rec_id` (`recipes_id`),
KEY `recipes_pos_ingredient_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;
My buggy Solution (doesn't support count from 1-n):
<?php
include 'db_connect.php';
$q = urldecode(mysql_real_escape_string($_GET['q']));
$parameter = explode ('$',$q);
$var = 0;
//print_r($parameter);
foreach($parameter as $ing)
{
//echo $ing;
$sql = "SELECT ingredients_id FROM INGREDIENTS WHERE name='".$ing."'";
$result = mysql_query($sql,$db) or exit('{"Data":null,"Message":null,"Code":500}');
$row = mysql_fetch_array($result);
$arr_id[$var] = $row['ingredients_id'];
$var++;
}
//print_r($arr_id);
$sql = "SELECT r.recipes_id FROM RECIPES r, RECIPES_POS rp WHERE r.recipes_id = rp.recipes_id ";
foreach($arr_id as $id)
{
$sql .= "AND rp.ingredients_id =".$id . " ";
}
//echo $sql;
$result = mysql_query($sql,$db) or exit('{"Data":null,"Message":null,"Code":500}');
mysql_close($db);
$rec;
while($row = mysql_fetch_array($result))
{
//echo "test";
$_GET['id'] = $row['recipes_id'];
$rec= include('get_recipe_byID.php');
}
//print_r(mysql_fetch_array($result));
if (count($arr_id) == 0)
{
echo '{"Data":null,"Message":null,"Code":404}';
die();
}
?>
I need a better solution for that chase.
Maybe SQL itself will help me to find the right recipes
thx
That query helped me a lot:
select r.recipes_id
from RECIPES r
inner join RECIPES_POS rp on r.recipes_id = rp.recipes_id
where rp.ingredients_id in (4, 6)
group by r.recipes_id
having count(distinct rp.ingredients_id) = 2
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.