I have a database of the following relations:
Bar(Name, Address, Licence)
Beer(Name,Manufacture)
Drinker(Name,Address)
Frequents(DrinkerName,BarName)
Likes(DrinkerName,BeerName)
Sells(BarName,BeerName,Amount)
Serves(BarName,BeerName)
The Sample DDL Statements:
CREATE TABLE `Bar` (
`Name` varchar(255) NOT NULL,
`Address` varchar(255) DEFAULT NULL,
`Licence` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Bar` (`Name`, `Address`, `Licence`) VALUES
('Deluxe', 'Luxvagen 2', 'Yes'),
('Grace', 'Gracevagen 2', 'Yes'),
('KrogBar', 'Barvagen 2', 'Yes');
CREATE TABLE `Beer` (
`Name` varchar(255) NOT NULL,
`Manufacture` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Beer` (`Name`, `Manufacture`) VALUES
('Carlsberg', 'Coppers'),
('Heiniken', 'Spendrups'),
('Miller', 'DaMill');
CREATE TABLE `Boor` (
`Name` varchar(255) NOT NULL,
`Age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `Drinker` (
`Name` varchar(255) NOT NULL,
`Address` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Drinker` (`Name`, `Address`) VALUES
('Alex', 'Överbar 2'),
('Bam', 'Påbar 2'),
('Emil', 'Mittibar 2'),
('Max', 'Ibar 2'),
('Petra', 'Förebar 2'),
('Rebecca', 'Efterbar 2'),
('Sam', 'Underbar 2');
CREATE TABLE `Frequents` (
`DrinkerName` varchar(255) NOT NULL DEFAULT '',
`BarName` varchar(255) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Frequents` (`DrinkerName`, `BarName`) VALUES
('Emil', 'Deluxe'),
('Max', 'Deluxe'),
('Rebecca', 'Deluxe'),
('Alex', 'Grace'),
('Petra', 'Grace'),
('Bam', 'KrogBar'),
('Sam', 'KrogBar');
CREATE TABLE `Likes` (
`DrinkerName` varchar(255) NOT NULL DEFAULT '',
`BeerName` varchar(255) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Likes` (`DrinkerName`, `BeerName`) VALUES
('Bam', 'Carlsberg'),
('Emil', 'Carlsberg'),
('Rebecca', 'Carlsberg'),
('Emil', 'Heiniken'),
('Max', 'Heiniken'),
('Petra', 'Heiniken'),
('Sam', 'Heiniken'),
('Alex', 'Miller');
CREATE TABLE `Sells` (
`BarName` varchar(100) DEFAULT NULL,
`BeerName` varchar(100) DEFAULT NULL,
`Amount` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Sells` (`BarName`, `BeerName`, `Amount`) VALUES
('KrogBar', 'Miller', 3),
('KrogBar', 'Carlsberg', 2),
('KrogBar', 'Heiniken', 1),
('Deluxe', 'Heiniken', 1);
CREATE TABLE `Serves` (
`BarName` varchar(255) NOT NULL DEFAULT '',
`BeerName` varchar(255) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Serves` (`BarName`, `BeerName`) VALUES
('Grace', 'Carlsberg'),
('KrogBar', 'Carlsberg'),
('Deluxe', 'Heiniken'),
('Grace', 'Heiniken'),
('KrogBar', 'Heiniken'),
('KrogBar', 'Miller');
I want to find drinkers that frequent only bars that serve beer that they like (the assumption is that each drinker frequents at least one bar).
How can I construct such a query? I know that I have to use Joins and Sub-queries, I am not new to either of them but all my implementations have not yielded the correct results.
Is this what you looking for;
Select DISTINCT bar.Name,bar.Address,frequents.DrinkerName, likes.BeerName
From
Bar
Join frequents on bar.Name = frequents.BarName
join sells on bar.name = sells.BarName
join likes on frequents.DrinkerName = likes.DrinkerName
Related
Not sure what i'm doing wrong here. Im trying to understand the relationships between tables? Please help thank you
DROP DATABASE IF EXISTS `sql_retail`;
CREATE DATABASE `sql_retail`;
USE `sql_retail`;
SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;
CREATE TABLE `RETAIL_ORDER` (
`OrderNumber` int(4) NOT NULL,
`StoreNumber` int(2) NOT NULL,
`StoreZip` char(9) NOT NULL,
`OrderMonth` char(12) NOT NULL,
`OrderYear` int(4) NOT NULL,
`OrderTotal` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `RETAIL_ORDER` VALUES (1000, 10, 98110, 'December', 2017, 445.00);
INSERT INTO `RETAIL_ORDER` VALUES (2000, 20, 02335, 'December', 2017, 310.00);
INSERT INTO `RETAIL_ORDER` VALUES (3000, 10, 98110, 'January', 2018, 480.00);
CREATE TABLE `ORDER_ITEM` (
`OrderNumber` int(11) NOT NULL,
`SKU` int(7) NOT NULL,
`Quantity` int(6) NOT NULL,
`Price` float(10) NOT NULL,
`Extended Price` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`),FOREIGN KEY(`OrderNumber`)REFERENCES RETAIL_ORDER(`OrderNumber`),
FOREIGN KEY(`SKU`)REFERENCES SKU_DATA(`SKU`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `ORDER_ITEM` VALUES (1000, 201000, 1, 300.00, 300.00);
INSERT INTO `ORDER_ITEM` VALUES (1000, 202000, 1, 130.00, 130.00);
INSERT INTO `ORDER_ITEM` VALUES (2000, 101100, 4, 50.00, 200.00);
INSERT INTO `ORDER_ITEM` VALUES (2000, 101200, 2, 50.00, 100.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 100200, 1, 300.00, 300.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 101100, 2, 50.00, 100.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 101200, 1, 50.00, 50.00);
CREATE TABLE `SKU_DATA` (
`SKU` int(11) NOT NULL,
`SKU_Description` varchar(50) NOT NULL,
`Department` varchar(20) NOT NULL,
`Buyer` varchar(15) NOT NULL,
PRIMARY KEY (`SKU`),FOREIGN KEY(`Buyer`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `SKU_DATA` VALUES (100100, 'Std. Scuba Tank, Yellow', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100200, 'Std. Scuba Tank, Magenta', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100300, 'Std. Scuba Tank, Light Blue', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100400, 'Std. Scuba Tank, Dark Blue', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100500, 'Std. Scuba Tank, Light Green', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100600, 'Std. Scuba Tank, Dark Green', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (101100, 'Dive Mask, Small Clear', 'Water Sports', 'Nancy Meyers');
INSERT INTO `SKU_DATA` VALUES (101200, 'Dive Mask, Med Clear', 'Water Sports', 'Nancy Meyers');
INSERT INTO `SKU_DATA` VALUES (201000, 'Half dome tent', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (202000, 'Half dome tent vestibule', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (203000, 'Half dome tent vestibule wide', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (301000, 'Light fly climbing harness', 'climbing', 'Jerry Martin');
INSERT INTO `SKU_DATA` VALUES (302000, 'Locking Carabiner, Oval', 'climbing', 'Jerry Martin');
CREATE TABLE `BUYER` (
`BuyerName` varchar(15) NOT NULL,
`Department` varchar(15) NOT NULL,
`Position` varchar(15) NOT NULL,
`Supervisor` varchar(15) NOT NULL,
PRIMARY KEY (`BuyerName`),FOREIGN KEY(`Supervisor`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `SKU_DATA` VALUES ('Cindy Lo', 'Purchasing', 'Buyer 2', 'Mary Smith');
INSERT INTO `SKU_DATA` VALUES ('Jerry Martin', 'Purchasing', 'Buyer 1', 'Cindo Lo');
INSERT INTO `SKU_DATA` VALUES ('Mary Smith', 'Purchasing', 'Manager','' );
INSERT INTO `SKU_DATA` VALUES ('Nancy Meyers', 'Purchasing', 'Buyer 1', 'Pete Hansen');
INSERT INTO `SKU_DATA` VALUES ('Pete Hansen', 'Purchasing', 'Buyer 3', 'Mary Smith');
You have some errors.
First you assign a foreign key to a table that don't exists yet and second you have duplicate values into your inserts for your primary keys.
I have fixed your table creation, check your insert datas.
Follow below approach to create your tables and then do the inserts:
DROP DATABASE IF EXISTS sql_retail ;
CREATE DATABASE sql_retail ;
USE sql_retail ;
SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;
CREATE TABLE `RETAIL_ORDER` (
`OrderNumber` int(4) NOT NULL,
`StoreNumber` int(2) NOT NULL,
`StoreZip` char(9) NOT NULL,
`OrderMonth` char(12) NOT NULL,
`OrderYear` int(4) NOT NULL,
`OrderTotal` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `ORDER_ITEM` (
`OrderNumber` int(11) NOT NULL,
`SKU` int(7) NOT NULL,
`Quantity` int(6) NOT NULL,
`Price` float(10) NOT NULL,
`Extended Price` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`),
FOREIGN KEY(`OrderNumber`)REFERENCES RETAIL_ORDER(`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `SKU_DATA` (
`SKU` int(11) NOT NULL,
`SKU_Description` varchar(50) NOT NULL,
`Department` varchar(20) NOT NULL,
`Buyer` varchar(15) NOT NULL,
PRIMARY KEY (`SKU`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
ALTER TABLE ORDER_ITEM ADD FOREIGN KEY(`SKU`)REFERENCES SKU_DATA(`SKU`);
CREATE TABLE `BUYER` (
`BuyerName` varchar(15) NOT NULL,
`Department` varchar(15) NOT NULL,
`Position` varchar(15) NOT NULL,
`Supervisor` varchar(15) NOT NULL,
PRIMARY KEY (`BuyerName`),
FOREIGN KEY(`Supervisor`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
ALTER TABLE SKU_DATA ADD FOREIGN KEY(`Buyer`)REFERENCES BUYER(`BuyerName`);
Demo: https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/28
While importing the sql data, it shows syntax error:
Here is my code:
CREATE TABLE IF NOT EXISTS `tblproduct` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`image` text NOT NULL,
`price` double(10,2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `product_code` (`code`)
)
INSERT INTO `tblproduct` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, '3D Camera', '3DcAM01', 'product-images/camera.jpg', 1500.00),
(2, 'External Hard Drive', 'USB02', 'product-images/external-hard-drive.jpg', 800.00),
(3, 'Wrist Watch', 'wristWear03', 'product-images/watch.jpg', 300.00);
I just confused with this, what is the exact error.
Can anyone help me to fix this? thanks in advance.
Looks like it's whole generated so there should be no errors. Try to add semicolon after create table syntax so each query is separated. Like this:
CREATE TABLE IF NOT EXISTS `tblproduct` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`image` text NOT NULL,
`price` double(10,2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `product_code` (`code`)
);
INSERT INTO `tblproduct` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, '3D Camera', '3DcAM01', 'product-images/camera.jpg', 1500.00),
(2, 'External Hard Drive', 'USB02', 'product-images/external-hard-drive.jpg', 800.00),
(3, 'Wrist Watch', 'wristWear03', 'product-images/watch.jpg', 300.00);
I need to be able to determine all of the people that were missing from attendance in a series of meetings.
I have a solution to figure this problem out with JS on the client's computer but I think it could be done more efficiently on the server.
Table A (people) -> Table B (attendance) <- Table C(meeting)
The attendance is a mapping table of items in table A and C.
See: http://sqlfiddle.com/#!8/6db81 for the exact schema
What I want is to determine all of the meetings that people have missed. That is there is no entry for that person for that meeting in the attendance table B.
Desired output should include a minimum of the lid (user id) and mid (meeting ID).
lid, firstname, lastname, mid, meeting_title, start.
The solution in JS would be to send the results of a cross of A and C, and the results of B to the client. Then remove all of the items in B from the cross of A and C.
CREATE TABLE IF NOT EXISTS `attendance` (
`mid` bigint(20) NOT NULL,
`sid` bigint(20) DEFAULT NULL,
`entered` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`lid` varchar(64) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`mid`,`lid`),
KEY `entered` (`entered`)
);
INSERT INTO `attendance` (`mid`, `sid`, `entered`, `lid`) VALUES
(5, NULL, '2013-12-25 21:44:27', '100'),
(5, NULL, '2013-12-25 21:44:19', '200'),
(5, NULL, '2013-12-25 21:44:21', '300'),
(9, NULL, '2013-12-26 14:49:49', '200'),
(9, NULL, '2013-12-26 07:10:34', '300');
CREATE TABLE IF NOT EXISTS `meetings` (
`mid` bigint(11) NOT NULL AUTO_INCREMENT,
`title` varchar(32) CHARACTER SET utf8 NOT NULL,
`start` datetime NOT NULL COMMENT 'registration start time',
`stop` datetime NOT NULL COMMENT 'registration stop time',
PRIMARY KEY (`mid`),
UNIQUE KEY `title` (`title`)
);
INSERT INTO `meetings` (`mid`, `title`, `start`, `stop`) VALUES
(5, 'Meeting 1', '2013-12-25 01:12:00', '2013-12-25 23:12:00'),
(9, 'Meeting 2', '2013-12-26 01:00:00', '2013-12-26 23:00:00');
CREATE TABLE IF NOT EXISTS `people` (
`sid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`lid` varchar(64) NOT NULL,
`firstname` varchar(64) NOT NULL,
`lastname` varchar(64) NOT NULL,
`title` varchar(5) DEFAULT NULL,
`address` varchar(128) DEFAULT NULL,
`city` varchar(64) DEFAULT NULL,
`state` varchar(2) DEFAULT NULL,
`zip` varchar(9) DEFAULT NULL,
`phone` varchar(12) DEFAULT NULL,
`cell` varchar(12) DEFAULT NULL,
`email` varchar(64) DEFAULT NULL,
PRIMARY KEY (`sid`),
UNIQUE KEY `sid` (`sid`),
UNIQUE KEY `lid` (`lid`)
);
INSERT INTO `people` (`sid`, `lid`, `firstname`, `lastname`, `title`, `address`, `city`, `state`, `zip`, `phone`, `cell`, `email`) VALUES
(1, '100', 'Fred', 'Jones', 'Mr.', 'Somewhere', 'City', 'AK', '12345', '123-123-1234', '123-123-1234', 'email#email.com'),
(2, '200', 'Wilma', 'Jones', 'Mrs.', '', 'City', '', '12346', '', NULL, '');
You have to join people and meetings table to get all possible combinations of meeting id and userid and then filter out only those, which are not present in attendance table.
SELECT a.lid,
b.mid
FROM people a
CROSS JOIN meetings b
WHERE NOT EXISTS (SELECT 1
FROM attendance c
WHERE c.mid = b.mid
AND c.lid = a.lid);
Fiddle
I am using the following sql statement to sum values from two columns from two different tables. The statement can output but not the desired result.
SELECT
SUM(`_income`.rate) AS Income,
SUM(`_expense`.rate) AS Expense,
SUM(_income.rate)-SUM(_expense.rate) AS Balance
FROM `_expense`, `_income`
My table is here:
CREATE TABLE IF NOT EXISTS `_expense` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`qnty` int(11) NOT NULL,
`rate` int(11) NOT NULL,
`date` date NOT NULL,
`CreatedByPHPRunner` int(11) NOT NULL,
`remarks` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table _expense
INSERT INTO `_expense` (`id`, `item`, `qnty`, `rate`, `date`, `CreatedByPHPRunner`, `remarks`) VALUES
(2, 'Maian', 2, 20, '2013-08-15', 0, 'A tui kher mai'),
(3, 'Battery', 1, 2100, '2013-08-15', 0, 'A lian chi');
--
-- Table structure for table _income
CREATE TABLE IF NOT EXISTS `_income` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`items` varchar(100) DEFAULT NULL,
`qnty` int(11) DEFAULT NULL,
`rate` int(11) DEFAULT NULL,
`date` date DEFAULT NULL,
`remarks` varchar(255) DEFAULT NULL,
`CreatedByPHPRunner` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table _income
INSERT INTO `_income` (`id`, `items`, `qnty`, `rate`, `date`, `remarks`, `CreatedByPHPRunner`) VALUES
(1, 'TV chhe siam', 1, 1500, '2013-08-15', 'Ka hniam hrep', NULL),
(2, 'First Star', 1, 25, '2013-08-15', 'A loose-in aw', NULL),
(3, 'Mobile Chhe siam', 2, 200, '2013-08-13', 'Nokia chhuak ho a nia', NULL),
(4, 'Internet hman man', 1, 1500, '2013-08-14', 'Ka net min hman sak a', NULL);
This should do it:
select income, expense, income-expense balance
from (select sum(rate) income
from _income) i
JOIN (select sum(rate) expense
from _expense) e
I suck at doing joins in MySQL, and I'm pretty sure this is what I need to make this work (though correct me if I'm wrong).
So I have two tables. Here's the SQL to set-up a simple database:
CREATE TABLE IF NOT EXISTS `wp_usermeta` (
`umeta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`meta_key` varchar(255) DEFAULT NULL,
`meta_value` longtext,
PRIMARY KEY (`umeta_id`),
KEY `user_id` (`user_id`),
KEY `meta_key` (`meta_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES
(1, 1, 'first_name', 'David'),
(2, 1, 'last_name', 'Jones'),
(3, 1, 'nickname', 'david'),
(4, 1, 'newsletter', '1'),
(5, 2, 'first_name', 'Greg'),
(6, 2, 'last_name', 'Smith'),
(7, 2, 'nickname', 'greg'),
(8, 2, 'newsletter', '0');
CREATE TABLE IF NOT EXISTS `wp_users` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_login` varchar(60) NOT NULL DEFAULT '',
`user_pass` varchar(64) NOT NULL DEFAULT '',
`user_nicename` varchar(50) NOT NULL DEFAULT '',
`user_email` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`ID`),
KEY `user_login_key` (`user_login`),
KEY `user_nicename` (`user_nicename`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`) VALUES
(1, 'david', '$^*#NNR&Y&)Mn9emfdfsdfsdfsd', 'david', 'david#domain.com'),
(2, 'greg', 'fdfsdfsdfsd$^*#NNR&Y&)Mn9em', 'greg', 'greg#domain.com');
...and I need to write a statement for a basic page that simply finds the users who have subscribed to the newsletter (meta_key with a meta_value of 1) and displays their first_name and user_email.
Thanks in advance.
It takes a fairly simple join;
SELECT user_login FROM wp_users
JOIN wp_usermeta
ON wp_users.id=wp_usermeta.user_id
WHERE meta_key='newsletter'
AND meta_value=1;
SQLfiddle to play with.