Insert data into 5 tables from a html form - sql

I have a problem how to place an order for a product, and then insert the order into 5 tables that are connected: ONE-TO-MANY, The tables are so connected that when the customer comes in the room, place an order for a product for e.g. coffee, or water it has to show in the orders page who placed the order, in which room does the customer sits and then the waiter gets the order into from the status is the product paid or not.
the tables are:
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`type_id` int(10) unsigned NOT NULL,
`username` varchar(50) DEFAULT NULL,
`password` varchar(32) DEFAULT NULL,
`first_name` varchar(100) DEFAULT NULL,
`last_name` varchar(100) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`picture` varchar(200) DEFAULT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_index1780` (`username`),
KEY `user_FKIndex1` (`type_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=71 ;
CREATE TABLE IF NOT EXISTS `order` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`status` int(11) DEFAULT NULL,
`room_id` int(11) NOT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`order_id`),
KEY `fk_order_room1` (`room_id`),
KEY `fk_order_user2` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`price` float DEFAULT NULL,
`picture` varchar(500) DEFAULT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
CREATE TABLE IF NOT EXISTS `room` (
`room_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`picture` varchar(450) DEFAULT NULL,
`description` text,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`room_id`),
KEY `fk_room_user1` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
CREATE TABLE IF NOT EXISTS `item_orders` (
`order_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`order_id`,`product_id`),
KEY `fk_order_has_product_product1` (`product_id`),
KEY `fk_order_has_product_order1` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `type_user` (
`type_id` int(10) unsigned NOT NULL,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`type_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now after I inner join them to place an order for a product nothing's happening.
The query is :
SELECT order.order_id,
user.first_name AS user,
product.name,
product.price,
item_orders.quantity,
product.price * item_orders.quantity AS sum,
room.name,
order.time,
order.status
FROM user, product, room, `order`, item_orders
WHERE user.user_id = room.user_id
AND order.room_id = room.room_id
AND order.order_id = item_orders.order_id
AND product.product_id = item_orders.product_id
This join is just fine it has only to enter a new join order_id = '$order_id' and that is it.

Provided you inserted data in all the tables referenced from your query:
INSERT INTO type_user (type_id) VALUES (1);
INSERT INTO user (user_id, type_id, first_name) VALUES (1, 1, 'cappie');
INSERT INTO room (room_id, user_id, name) VALUES (10, 1, 'Room 10');
INSERT INTO `order` (order_id, room_id, user_id, status) VALUES (1 , 10, 1, 3);
INSERT INTO product (product_id, name, price) VALUES (100, 'Product A', 99.99);
INSERT INTO item_orders (order_id, product_id, quantity) VALUES (1, 100, 15);
The query you provided (in the comments) will run fine and return (almost) correct Results :
| ORDER_ID | USER | NAME | PRICE | QUANTITY | SUM | TIME | STATUS |
--------------------------------------------------------------------------------------------------------------------------
| 1 | cappie | Product A | 99.98999786377 | 15 | 1499.849967956543 | August, 08 2013 07:03:34+0000 | 3 |
You have a floating point rounding error, but that's a story for another day.
Here is the full SQL Fiddle.

Related

SQL find all records from one table, but only the most recent record from a linked table

I am looking to select all records from my userrecords table and then find the corresponding most recent record from my checkins table.
I need to do this so that I can display whether the user is checked-in or checked-out for the current day and campus.
The outdatetime is a NULL value when the user is currently checked-in, and the query should take into account the current date so that only checkin records for the current date are considered.
My table setup is like so:
CREATE TABLE `userrecords` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(45) NOT NULL,
`surname` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`phone` varchar(15) DEFAULT NULL,
`password` char(64) DEFAULT NULL,
`userlevel` int(1) NOT NULL,
`suspended` varchar(1) DEFAULT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`lastcheckdate` datetime DEFAULT NULL,
`maincampus` varchar(3) DEFAULT NULL,
`lastlogin` datetime DEFAULT NULL,
`staffid` varchar(6) DEFAULT NULL,
PRIMARY KEY (`userid`),
UNIQUE KEY `email_UNIQUE` (`email`),
UNIQUE KEY `userid_UNIQUE` (`userid`)
) ENGINE=InnoDB AU
CREATE TABLE `checkins` (
`recordid` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`campusid` int(11) NOT NULL,
`indatetime` datetime DEFAULT NULL,
`outdatetime` datetime DEFAULT NULL,
PRIMARY KEY (`recordid`),
KEY `campusid_idx` (`campusid`),
KEY `userid_idx` (`userid`),
CONSTRAINT `campusid` FOREIGN KEY (`campusid`) REFERENCES `campus` (`campusid`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `userid` FOREIGN KEY (`userid`) REFERENCES `userrecords` (`userid`) ON DELETE CASCADE ON UPDATE CASCADE
My query is so far:
SELECT userid,firstname,surname,email,lastcheckdate FROM userrecords WHERE userlevel=0
You can use window functions:
select ur.*, c.*
from userrecords ur left join
(select c.*,
row_number() over (partition by userid order by indatetime desc) as seqnum
from checkins c
) c
on ur.userid = c.userid and ur.seqnum = 1;

Cannot add or update a child row: a foreign key constraint fails (Clubs and Users)

User Table
CREATE TABLE IF NOT EXISTS `users` (
`userId` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`firstname` varchar(25) NOT NULL,
`lastname` varchar(25) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
`addressLine1` varchar(80) NOT NULL,
`addressLine2` varchar(80) NOT NULL,
`town` varchar(30) NOT NULL,
`county` varchar(30) NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=55 ;
Club Table
CREATE TABLE IF NOT EXISTS `clubs` (
`clubId` int(11) NOT NULL AUTO_INCREMENT,
`clubName` varchar(100) NOT NULL,
`startTime` varchar(5) NOT NULL,
`finishTime` varchar(5) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`clubId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
memberid Table
CREATE TABLE IF NOT EXISTS `membersid` (
`memberId` int(11) NOT NULL AUTO_INCREMENT,
`clubId` int(11) NOT NULL,
`userId` int(11) NOT NULL,
PRIMARY KEY (`memberId`,`clubId`,`userId`),
UNIQUE KEY `memberId` (`memberId`),
KEY `clubId` (`clubId`),
KEY `userId` (`userId`),
KEY `clubId_2` (`clubId`),
KEY `clubId_3` (`clubId`),
KEY `userId_2` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
DAO
String query = "INSERT INTO membersid( userId, clubId ) VALUES ( ?,? )";
Keep getting error Cannot add or update a child row: a foreign key constraint fails
If someone could be that would be great:)
Your keys in the membersid table (please change that name to members) are messed up. Try
CREATE TABLE IF NOT EXISTS members
(
`memberId` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`clubId` int(11) NOT NULL,
`userId` int(11) NOT NULL,
UNIQUE KEY (`clubId`,`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

SQL delete based on query

How do I delete all laptops made by a manufacturer that doesn’t make PCs?
I currently have the following tables:
CREATE TABLE `Device` (
`model` varchar(50) NOT NULL DEFAULT '',
`speed` double DEFAULT NULL,
`RAM` int(11) DEFAULT NULL,
`HD` int(11) DEFAULT NULL,
`list_price` double DEFAULT NULL,
`type` varchar(45) NOT NULL,
`screen` varchar(45) DEFAULT NULL,
PRIMARY KEY (`model`,`type`)
);
INSERT INTO `Device` VALUES
('GATE TOP',2.5,2000,500,1000,'LAPTOP','12'),
('GATE TOWER',2.5,2000,500,1000,'DESKTOP',NULL),
('HELLO TOWER',3.5,8000,1000,1299,'DESKTOP',NULL),
('MACBOOK AIR',2.5,2048,500,599,'LAPTOP','11'),
('MACBOOK PRO',3.5,8000,1000,1299,'LAPTOP','19'),
('PAAP',2.5,2048,500,599,'DESKTOP',NULL),
('TOWER',3,3100,400,2499,'DESKTOP',NULL),
('ULTRA TOWER',6,5000,1000,8999,'DESKTOP',NULL),
('VAIO',2.5,2000,500,569,'LAPTOP','12'),
('VAIO TOWER',2.5,2000,500,569,'DESKTOP',NULL);
CREATE TABLE `Product` (
`manu_Name` varchar(50) NOT NULL DEFAULT '',
`model` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`manu_Name`,`model`),
KEY `Product` (`model`),
CONSTRAINT `Product_ibfk_1` FOREIGN KEY (`manu_Name`)
REFERENCES `Manufacturer` (`name`),
CONSTRAINT `Product_ibfk_2` FOREIGN KEY (`model`)
REFERENCES `Device` (`model`)
);
INSERT INTO `Product` VALUES
('GATEWAY','GATE TOP'),('GATEWAY','GATE TOWER'),
('ACER','HELLO TOWER'),('APPLE','MACBOOK AIR'),
('APPLE','MACBOOK PRO'),('ACER','PAAP'),
('DELL','TOWER'),('SONY','VAIO'),
('SONY','VAIO TOWER');
CREATE TABLE `Manufacturer` (
`name` varchar(50) NOT NULL,
`country` varchar(50) DEFAULT NULL,
`phone` varchar(10) DEFAULT NULL,
PRIMARY KEY (`name`)
);
INSERT INTO `Manufacturer` VALUES
('ACER','TAIWAN','9024801111'),
('APPLE','UNITED STATES','9028189125'),
('DELL','UNITED STATES','9025551234'),
('GATEWAY','UNITED STATES','8705551698'),
('SONY','JAPAN','0123456789'),
('TOSHIBA','JAPAN','1235553560');
The delete statement would be something like this:
delete from `Device` where `model` in (
select `model` from `Product` where `manu_Name` in ('APPLE')
);

How to use subqueries in MySQL

I have two tables.
Table user:
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(20) NOT NULL AUTO_INCREMENT,
`ud_id` varchar(50) NOT NULL,
`name` text NOT NULL,
`password` text NOT NULL,
`email` varchar(200) NOT NULL,
`image` varchar(150) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB
and mycatch:
CREATE TABLE IF NOT EXISTS `mycatch` (
`catch_id` int(11) NOT NULL AUTO_INCREMENT,
`catch_name` text NOT NULL,
`catch_details` text NOT NULL,
`longitude` float(10,6) NOT NULL,
`latitude` float(10,6) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`image` varchar(150) NOT NULL,
`user_id` int(20) NOT NULL,
PRIMARY KEY (`catch_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB;
ALTER TABLE `mycatch`
ADD CONSTRAINT `mycatch_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;
My goal is: I want to retrieve longitude and latitude from mycatch against given ud_id (from user) and catch_id (from mycatch) where ud_id = given ud_id and catch_id > given catch_id.
I used the query but fail to retrieve
SELECT ud_id=$ud_id FROM user
WHERE user_id =
(
SELECT user_id,longitude,latitude from mycatch
WHERE catch_id>'$catch_id'
)
The error is:
#1241 - Operand should contain 1 column(s)
First, try not to use subqueries at all, they're very slow in MySQL.
Second, a subquery wouldn't even help here. This is a regular join (no, Mr Singh, not an inner join):
SELECT ud_id FROM user, mycatch
WHERE catch_id>'$catch_id'
AND user.user_id = mycatch.user_id
Select m.longitude,m.latitude from user u left join mycatch m
on u.user_id =m.user_id
where u.ud_id=$ud_id and
m.catch_id >$catch_id

SQL: Subquery assistance

I'm trying to SELECT two values in one statement instead of two statements. The first statement counts how many entries won for a specific contest that has an id of 18. The second statement counts the total quantity of prizes for that contest.
Query 1:
SELECT
COUNT(*) FROM entries
WHERE entries.contest=18
AND entries.won=1
Query 2
SELECT SUM( quantity ) FROM prizes WHERE contest=18
I want to have both so I could compare them on the server-side and act upon that comparison.. So if we had say 3 entrants who won the 18th contest and the total quantity of prizes for the 18th contest is 5, do something...
Schema:
CREATE TABLE `entries` (
`id` int(2) unsigned NOT NULL auto_increment,
`message_id` bigint(8) unsigned default NULL,
`user` int(2) unsigned default NULL,
`username` varchar(50) NOT NULL,
`contest` int(2) unsigned default NULL,
`message` text,
`icon` text,
`twitter_url` text,
`follower` int(2) unsigned default NULL,
`entry_date` timestamp NOT NULL default '0000-00-00 00:00:00',
`won` int(1) default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
CREATE TABLE `prizes` (
`id` int(2) unsigned NOT NULL auto_increment,
`name` varchar(25) NOT NULL,
`contest` int(2) NOT NULL,
`quantity` int(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
There is no users table because I control the entries, and I'm pretty sure I won't get any duplicates so that's why the user name, etc is stored for the entry row.
As the queries doesn't have anything in common at all, you would use two subqueries to get them in the same result:
select
(select count(*) from entries where contest = 18 and won = 1) as wins,
(select sum(quantity) from prizes where contest = 18) as quantity