Find all missing mapping table entries - mysql

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

Related

SQL query not returning correct result using three table together?

I have 3 tables in which tbl_user_signup_info, tbl_main_lead_info and tbl_campaign_info, I need a result in which it display info such that each row display the lead id and campaign id added by corresponding registered users of the tbl_user_signup_info and display should be like User_Id, Lead_Id, Campaign_ID.
Actually i want Total number of leads added by particular user with there Lead Id and Total number of campaign added by that user with there Campaign_Id using those 3 tables.
But i am lacking to form SQL query.
My Result are as below which are wrong:
Table structure
--
-- Table structure for table `tbl_campaign_info`
--
DROP TABLE IF EXISTS `tbl_campaign_info`;
CREATE TABLE IF NOT EXISTS `tbl_campaign_info` (
`Campaign_Id` int(100) NOT NULL AUTO_INCREMENT,
`CampaignName` varchar(200) NOT NULL,
`CampaignStatus` varchar(200) NOT NULL,
`CampaignDescription` varchar(200) DEFAULT NULL,
`CampaignOwnerNotes` varchar(200) DEFAULT NULL,
`CampaignAdminNotes` varchar(200) DEFAULT NULL,
`CampaignStartDate` date NOT NULL,
`CampaignEndDate` date NOT NULL,
`CampaignLead_Id` int(100) NOT NULL,
`CampaignAddedBy` int(100) NOT NULL,
`CampaignAddedOn` date DEFAULT NULL,
UNIQUE KEY `Campaign_Id` (`Campaign_Id`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=latin1;
--
-- Table structure for table `tbl_main_lead_info`
--
DROP TABLE IF EXISTS `tbl_main_lead_info`;
CREATE TABLE IF NOT EXISTS `tbl_main_lead_info` (
`Lead_Id` int(100) NOT NULL AUTO_INCREMENT,
`FirstName` varchar(100) DEFAULT NULL,
`LastName` varchar(100) DEFAULT NULL,
`Company` varchar(100) DEFAULT 'NA',
`Website` varchar(100) DEFAULT 'NA',
`Designation` varchar(100) DEFAULT 'NA',
`Linkedin` varchar(100) DEFAULT 'NA',
`Email` varchar(100) DEFAULT NULL,
`Phone` varchar(100) DEFAULT NULL,
`State` varchar(100) DEFAULT NULL,
`Country` varchar(100) DEFAULT NULL,
`TechArea` varchar(100) DEFAULT NULL,
`FirmType` varchar(100) DEFAULT NULL,
`FirmSize` varchar(100) DEFAULT NULL,
`LastContactDate` date DEFAULT NULL,
`NextContactDate` date DEFAULT NULL,
`LeadDescription` varchar(200) DEFAULT NULL,
`OwnerNotes` varchar(200) DEFAULT NULL,
`SetReminder` date DEFAULT NULL,
`AdminNotes` varchar(200) DEFAULT NULL,
`LeadStatus` varchar(100) DEFAULT NULL,
`LeadAddedBy` int(100) NOT NULL,
`LeadAddedOn` datetime DEFAULT NULL,
PRIMARY KEY (`Lead_Id`),
UNIQUE KEY `FirstName` (`FirstName`,`LastName`,`Company`,`Website`,`Designation`,`Linkedin`,`Email`,`Phone`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_main_lead_info`
--
INSERT INTO `tbl_main_lead_info` (`Lead_Id`, `FirstName`, `LastName`, `Company`, `Website`, `Designation`, `Linkedin`, `Email`, `Phone`, `State`, `Country`, `TechArea`, `FirmType`, `FirmSize`, `LastContactDate`, `NextContactDate`, `LeadDescription`, `OwnerNotes`, `SetReminder`, `AdminNotes`, `LeadStatus`, `LeadAddedBy`, `LeadAddedOn`) VALUES
(15, 'John', 'Doe', 'test', 'test', 'test', 'test', 'test', 'test', 'Texas', 'USA', 'test', 'Corporate', '11-50', '2020-01-09', '2020-01-10', 'Testing Description of Lead information', NULL, '2020-01-11', 'This need to be confidential by admin', 'Active', 18, '2020-01-09 16:07:17');
--
-- Dumping data for table `tbl_campaign_info`
--
INSERT INTO `tbl_campaign_info` (`Campaign_Id`, `CampaignName`, `CampaignStatus`, `CampaignDescription`, `CampaignOwnerNotes`, `CampaignAdminNotes`, `CampaignStartDate`, `CampaignEndDate`, `CampaignLead_Id`, `CampaignAddedBy`, `CampaignAddedOn`) VALUES
(16, 'Test', 'Active', 'Test', NULL, 'This is admin notes and need to be kept confidential', '2020-01-09', '2020-01-10', 15, 18, '2020-01-09'),
(17, 'Test', 'Active', 'Test ', NULL, 'NA', '2020-01-10', '2020-01-10', 15, 18, '2020-01-09');
--
-- Table structure for table `tbl_user_signup_info`
--
DROP TABLE IF EXISTS `tbl_user_signup_info`;
CREATE TABLE IF NOT EXISTS `tbl_user_signup_info` (
`User_Id` int(50) NOT NULL AUTO_INCREMENT,
`UserEmail` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`UserName` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`UserPassword` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`Admin` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`User_Id`) USING BTREE,
UNIQUE KEY `Email` (`UserEmail`),
UNIQUE KEY `UserName` (`UserName`),
UNIQUE KEY `UserEmail` (`UserEmail`,`UserName`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `tbl_user_signup_info`
--
INSERT INTO `tbl_user_signup_info` (`User_Id`, `UserEmail`, `UserName`, `UserPassword`, `Admin`) VALUES
(18, 'test#gmail.com', 'test', 'test', 1),
(22, 'test1#gmail.com', 'test1', 'test1', 0),
(23, 'test2#gmail.com', 'test2', 'test2', 0);
COMMIT;
and My SQl Query is as below:
SELECT User_Id, Campaign_Id, Lead_Id
FROM tbl_campaign_info AS C,
tbl_main_lead_info AS M,
tbl_user_signup_info AS U
WHERE C.CampaignAddedBy IN ( SELECT User_Id
FROM tbl_user_signup_info AS U,
tbl_campaign_info AS C
WHERE U.User_Id = C.CampaignAddedBy)
AND M.LeadAddedBy IN (SELECT User_Id
FROM tbl_user_signup_info AS U,
tbl_main_lead_info AS M
WHERE U.User_Id = M.LeadAddedBy )
If I understand correctly, you want users campaign counts and lead counts per user. So, select campaign counts, select lead counts, join them.
You could use a full outer join of the two results for this (thus getting only those users that have at least one campain or lead), but MySQL doesn't support it. I take it that tbl_user_signup_info contains one row per user, though, so you can use this as a base table. The following query gives you a result for every user in that table.
select
u.user_id,
coalesce(c.total, 0) as campaign_count,
coalesce(l.total, 0) as lead_count
from tbl_user_signup_info u
left join
(
select campaignaddedby, count(*) as total
from tbl_campaign_info
group by campaignaddedby
) c on c.campaignaddedby = u.user_id
left join
(
select leadaddedby, count(*) as total
from tbl_main_lead_info
group by leadaddedby
) l on l.leadaddedby = u.user_id
order by u.user_id;
It seems like you can only use JOIN.
SELECT U.User_Id, Campaign_Id, Lead_Id
FROM tbl_user_signup_info AS U
JOIN tbl_campaign_info AS C ON U.User_Id = C.CampaignAddedBy
JOIN tbl_main_lead_info AS M ON U.User_Id = M.LeadAddedBy
Actually i want Total number of leads added by particular user with
there Lead Id and Total number of campaign added by that user with
there Campaign_Id using those 3 tables.
Try this:
SELECT
X.USER_ID,
X.LeadCount,
IF(Y.LEAD_ID IS NULL, 0, Y.LEAD_ID) LEAD_ID,
IF(Y.CampaignCount IS NULL, 0, Y.CampaignCount) CampaignCount
FROM (
SELECT
U.User_ID, COUNT(DISTINCT LEAD_ID) LeadCount
FROM
tbl_user_signup_info U
LEFT JOIN
tbl_main_lead_info M
ON (U.User_Id = M.LeadAddedBy)
GROUP BY
U.USER_ID
) X
LEFT JOIN
(
SELECT
M.LeadAddedBy, M.LEAD_ID, COUNT(DISTINCT Campaign_Id) CampaignCount
FROM
tbl_campaign_info C
LEFT JOIN
tbl_main_lead_info M
ON (C.CampaignAddedBy = M.LeadAddedBy)
GROUP BY
M.LeadAddedBy, M.LEAD_ID
) Y
ON (
X.USER_ID = Y.LeadAddedBy
)
SQL Fiddle link: http://sqlfiddle.com/#!9/4e138/40

Join two tables where one table name is inside the other table

I am registering various properties in the property table. Depending on the type of property, three new tables namely apartment, villa, land is used to store specific data. So what I have is the a master table which holds property URL, Property type, Ref table name (any of the three sub table name - apartment, villa, land) and the ref id which is the primary autoincrement key of the sub tables.
I tried the three seperated select query and Union of the result. The drawback is that the results will be mostly from the first table name uses among the three.
function getMyProperty() {
$tables = $this->getPropertyTables();
$result = array();
foreach ($tables as $key => $table) {
$this->db->select('a.main_heading, a.sub_heading, a.location, a.about_property, a.property_price, a.available_from, p.property_url');
$this->db->from('property p');
$this->db->join($table . ' a', 'p.ref_id = a.id');
$this->db->where('p.posted_by', $this->session->user_id);
$this->db->where('p.ref_table', $this->db->dbprefix($table));
$query = $this->db->get();
$res = $query->result();
$result = array_merge($result, $res);
}
return $result;
}
DB SCHEMA
CREATE TABLE `apartment` (
`id` int(11) NOT NULL,
`main_heading` varchar(256) NOT NULL,
`sub_heading` text NOT NULL,
`build_up_area` int(11) NOT NULL,
`carpet_area` int(11) NOT NULL,
`no_of_bedrooms` int(11) NOT NULL,
`bathrooms` int(11) NOT NULL,
`available_from` date NOT NULL,
`furnishing` varchar(256) NOT NULL,
`facing` varchar(100) NOT NULL,
`flooring` varchar(256) NOT NULL,
`parking` varchar(256) NOT NULL,
`width_of_facing_road` varchar(100) NOT NULL,
`property_age` int(11) NOT NULL,
`property_price` decimal(16,2) NOT NULL DEFAULT '0.00',
`address` text NOT NULL,
`about_property` text NOT NULL,
`location` varchar(256) NOT NULL,
`amenities` text NOT NULL,
`owner_name` varchar(256) NOT NULL,
`owner_email` varchar(256) NOT NULL,
`owner_phone` varchar(100) NOT NULL,
`active` enum('Y','N') NOT NULL DEFAULT 'Y'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
INSERT INTO `apartment` (`id`, `main_heading`, `sub_heading`, `build_up_area`, `carpet_area`, `no_of_bedrooms`, `bathrooms`, `available_from`, `furnishing`, `facing`, `flooring`, `parking`, `width_of_facing_road`, `property_age`, `property_price`, `address`, `about_property`, `location`, `amenities`, `owner_name`, `owner_email`, `owner_phone`, `active`) VALUES
(2, 'My Appartment', 'Place', 255, 400, 4, 4, '2019-08-08', 'semi', 'north', 'vitrified', '2', '15', 15, '15.00', 'ghkgkgk', 'jkhjkhjk', 'Kochi', '', 'Agent', 'abc#edg.com', '9876543210', 'Y'),
(3, 'My Appartment 2', 'Test', 255, 400, 4, 4, '2019-08-08', 'semi', 'north', 'vitrified', '2', '15', 15, '15.00', 'ghkgkgk', 'jkhjkhjk', 'Kochi', '', 'Agent', 'abc#edg.com', '9876543210', 'Y');
CREATE TABLE `land` (
`id` int(11) NOT NULL,
`main_heading` varchar(256) NOT NULL,
`sub_heading` text NOT NULL,
`plot_area` int(11) NOT NULL,
`gated_colony` int(11) NOT NULL,
`open_sides` int(11) NOT NULL,
`available_from` date NOT NULL,
`dimensions` varchar(256) NOT NULL,
`facing` varchar(100) NOT NULL,
`boundary_wall` varchar(256) NOT NULL,
`parking` varchar(256) NOT NULL,
`width_of_facing_road` varchar(100) NOT NULL,
`property_age` int(11) NOT NULL,
`property_price` decimal(16,2) NOT NULL DEFAULT '0.00',
`address` text NOT NULL,
`about_property` text NOT NULL,
`location` varchar(256) NOT NULL,
`owner_name` varchar(256) NOT NULL,
`owner_email` varchar(256) NOT NULL,
`owner_phone` varchar(100) NOT NULL,
`active` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
CREATE TABLE `property` (
`property_id` int(11) NOT NULL,
`posted_by` int(11) NOT NULL,
`post_type` enum('RENT','SELL','LEASE') NOT NULL,
`property_type` enum('VILLA','APARTMENT','LAND') NOT NULL,
`property_url` varchar(50) NOT NULL,
`ref_table` varchar(50) NOT NULL DEFAULT '',
`ref_id` int(11) NOT NULL DEFAULT '0',
`posted_on` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
INSERT INTO `property` (`property_id`, `posted_by`, `post_type`, `property_type`, `property_url`, `ref_table`, `ref_id`, `posted_on`) VALUES
(4, 1, 'SELL', 'VILLA', 'lyohlp', 'villa', 2, '2019-08-05'),
(5, 1, 'SELL', 'APARTMENT', 'cvbdit', 'apartment', 2, '2019-08-05'),
(6, 2, 'SELL', 'APARTMENT', 'qwerty', 'apartment', 3, '2019-08-05'),
(7, 3, 'RENT', 'VILLA', 'asdfgh', 'villa', 3, '2019-08-05');
CREATE TABLE `villa` (
`id` int(11) NOT NULL,
`main_heading` varchar(256) NOT NULL,
`sub_heading` text NOT NULL,
`build_up_area` int(11) NOT NULL,
`carpet_area` int(11) NOT NULL,
`no_of_bedrooms` int(11) NOT NULL,
`bathrooms` int(11) NOT NULL,
`available_from` date NOT NULL,
`furnishing` varchar(256) NOT NULL,
`facing` varchar(100) NOT NULL,
`flooring` varchar(256) NOT NULL,
`total_area` varchar(256) NOT NULL,
`width_of_facing_road` varchar(100) NOT NULL,
`property_age` int(11) NOT NULL,
`property_price` decimal(16,2) NOT NULL DEFAULT '0.00',
`address` text NOT NULL,
`about_property` text NOT NULL,
`location` varchar(256) NOT NULL,
`amenities` text NOT NULL,
`owner_name` varchar(256) NOT NULL,
`owner_email` varchar(256) NOT NULL,
`owner_phone` varchar(100) NOT NULL,
`active` enum('Y','N') NOT NULL DEFAULT 'Y'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
INSERT INTO `villa` (`id`, `main_heading`, `sub_heading`, `build_up_area`, `carpet_area`, `no_of_bedrooms`, `bathrooms`, `available_from`, `furnishing`, `facing`, `flooring`, `total_area`, `width_of_facing_road`, `property_age`, `property_price`, `address`, `about_property`, `location`, `amenities`, `owner_name`, `owner_email`, `owner_phone`, `active`) VALUES
(2, 'My Villa', 'Kakkanad', 54, 5, 4, 4, '2019-08-06', 'semi', 'west', 'not-vitrified', '111', '10', 0, '12.00', 'fhgfgh', 'ghfghf', 'Kochi', 'car_parking,water_supply,garden,fitness_center,shower,fridge', 'dfdfdf', 'abc#edg.com', '9876543210', 'Y'),
(3, 'My Villa 2', 'Place', 54, 5, 4, 4, '2019-08-06', 'semi', 'west', 'not-vitrified', '111', '10', 0, '12.00', 'fhgfgh', 'ghfghf', 'Kochi', 'car_parking,water_supply,garden,fitness_center,shower,fridge', 'dfdfdf', 'abc#edg.com', '9876543210', 'Y');
ALTER TABLE `apartment`
ADD PRIMARY KEY (`id`);
ALTER TABLE `land`
ADD PRIMARY KEY (`id`);
ALTER TABLE `property`
ADD PRIMARY KEY (`property_id`),
ADD KEY `ref_id` (`ref_id`);
ALTER TABLE `villa`
ADD PRIMARY KEY (`id`);
ALTER TABLE `apartment`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
ALTER TABLE `land`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `property`
MODIFY `property_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
ALTER TABLE `villa`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
I expect result based on the decreasing of post date irrespective of the order of the table I provided.
As we know only one of the type can be mapped with the property.
So data will be generated from one table(which store details of that property type) only, other tables will produce null.
A great way to pick data from multiple columns if only one of them is not null, is using CONCAT_WS or COALESCE.
SELECT
P.property_id, P.property_url,
CONCAT_WS('', V.main_heading, A.main_heading, L.main_heading) AS main_heading,
CONCAT_WS('', V.sub_heading, A.sub_heading, L.sub_heading) AS sub_heading,
CONCAT_WS('', V.location, A.location, L.location) AS location,
CONCAT_WS('', V.about_property, A.about_property, L.about_property) AS about_property,
CONCAT_WS('', V.property_price, A.property_price, L.property_price) AS property_price,
CONCAT_WS('', V.available_from, A.available_from, L.available_from) AS available_from,
P.posted_on
FROM property P
LEFT JOIN villa V ON P.ref_table = 'villa' AND P.ref_id = V.id
LEFT JOIN apartment A ON P.ref_table = 'apartment' AND P.ref_id = A.id
LEFT JOIN land L ON P.ref_table = 'land' AND P.ref_id = L.id
ORDER BY P.posted_on DESC;
Using COALESCE at place of CONCAT_WS would be like:
COALESCE(V.main_heading, A.main_heading, L.main_heading) AS main_heading
Reference: MySQL Function: COALESCE, MySQL Function: CONCAT_WS
You can integrate the following query in CI instead of looping in php. It provides single set array.
SELECT
a.*,
b.id,
c.id,
d.id
FROM
`property` AS a
LEFT JOIN `apartment` AS b
ON a.`ref_id` = b.id
AND a.`ref_table` = 'apartment'
LEFT JOIN `land` AS c
ON a.`ref_id` = c.id
AND a.`ref_table` = 'land'
LEFT JOIN `villa` AS d
ON a.`ref_id` = d.id
AND a.`ref_table` = 'villa'
ORDER BY a.`posted_by` DESC ;
Here, joining tables respective of constant table name and other fields will return null.Those conditions can map in PHP code.
Note : add necessary columns in select what you needed.
add this condition too : $this->db->where('p.posted_by', $this->session->user_id); in query

Why don't I have all permissions when I am logged on as root?

This is a GCP MySQL Cloud instance, MySQL 2nd Gen 5.7. Google installed and configured it.
I am logged in as root:
When I run a script to create schemas, tables, and views, I get this error:
Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation
Here are the permissions assigned to root:
Here is the SQL that fails, in the form of a stored procedure:
CREATE DEFINER=`root`#`%` PROCEDURE `CreateFullCoverageTestCase`()
BEGIN
-- Create all the elements of the Full Coverage Test Case
-- *********************
-- Schema Store
-- *********************
Begin
DROP Schema if exists `store`;
END;
BEGIN
CREATE SCHEMA `store` ;
CREATE TABLE `store`.`city` (
`CityID` int(11) NOT NULL AUTO_INCREMENT,
`City` varchar(45) NOT NULL,
PRIMARY KEY (`CityID`),
UNIQUE KEY `City_UNIQUE` (`City`));
INSERT INTO store.city (City) VALUES('Cincinnati');
INSERT INTO store.city (City) VALUES('Columbus');
INSERT INTO store.city (City) VALUES('Kokomo');
INSERT INTO store.city (City) VALUES('Hillsdale');
INSERT INTO store.city (City) VALUES('Lexington');
INSERT INTO store.city (City) VALUES('Oxford');
CREATE TABLE `store`.`state` (
`StateID` int(11) NOT NULL AUTO_INCREMENT,
`State` varchar(45) NOT NULL,
`StateAbbreviation` varchar(2) NOT NULL,
PRIMARY KEY (`StateID`),
UNIQUE KEY `StateAbbreviation_UNIQUE` (`StateAbbreviation`),
UNIQUE KEY `State_UNIQUE` (`State`),
UNIQUE KEY `StateID_UNIQUE` (`StateID`));
INSERT INTO store.state (State, StateAbbreviation) VALUES('Indiana', 'IN');
INSERT INTO store.state (State, StateAbbreviation) VALUES('Kentucky', 'KY');
INSERT INTO store.state (State, StateAbbreviation) VALUES('Michigan', 'MI');
INSERT INTO store.state (State, StateAbbreviation) VALUES('Ohio', 'OH');
CREATE TABLE `store`.`store` (
`StoreID` int(11) NOT NULL AUTO_INCREMENT,
`StoreNumber` varchar(10) NOT NULL,
`AddressLine1` varchar(45) NOT NULL,
`AddressLine2` varchar(45) DEFAULT NULL,
`CityID` int(11) NOT NULL,
`StateID` int(11) NOT NULL,
`ZipCode` varchar(10) NOT NULL,
PRIMARY KEY (`StoreID`),
UNIQUE KEY `StoreNumber_UNIQUE` (`StoreNumber`));
INSERT INTO store.store (StoreNumber, AddressLine1, CityID, StateID, ZipCode) VALUES('S000000001', '111 Main', 1, 4, '45255-1321');
INSERT INTO store.store (StoreNumber, AddressLine1, CityID, StateID, ZipCode) VALUES('S000000002', '817 Nordyke', 1, 4, '45103-0000');
INSERT INTO store.store (StoreNumber, AddressLine1, CityID, StateID, ZipCode) VALUES('S000000003', '123 Green', 6, 4, '45056-0000');
End;
-- *********************
-- Schema HR (Human Resources)
-- *********************
BEGIN
DROP Schema if exists `hr`;
END;
BEGIN
CREATE SCHEMA `hr` ;
CREATE TABLE `hr`.`employee` (
`EmployeeID` INT NOT NULL AUTO_INCREMENT,
`LastName` VARCHAR(45) NOT NULL,
`FirstName` VARCHAR(45) NOT NULL,
`EmployeeNumber` VARCHAR(10) NOT NULL,
`AddressLine1` VARCHAR(45) NOT NULL,
`AddressLine2` VARCHAR(45) NULL,
`City` VARCHAR(45) NOT NULL,
`State` VARCHAR(2) NOT NULL,
`ZipCode` VARCHAR(10) NOT NULL,
PRIMARY KEY (`EmployeeID`),
UNIQUE INDEX `EmployeeNumber_UNIQUE` (`EmployeeNumber` ASC));
INSERT INTO hr.employee (lastName, firstName, EmployeeNumber, AddressLine1, City, State, ZipCode) VALUES('Cheaney', 'Calbert', 'E000000001', '17th Street', 'Bloomington', 'IN', '47405');
INSERT INTO hr.employee (lastName, firstName, EmployeeNumber, AddressLine1, City, State, ZipCode) VALUES('Reynolds', 'Chris', 'E000000002', 'Fee Street', 'Bloomington', 'IN', '47405');
END;
-- *********************
-- Products for sale
-- *********************
BEGIN
DROP Schema if exists `product`;
END;
BEGIN
CREATE SCHEMA `product` ;
CREATE TABLE `product`.`manufacturer` (
`ManufacturerID` int(11) NOT NULL AUTO_INCREMENT,
`Manufacturer` varchar(45) NOT NULL,
`Comment` varchar(1000) DEFAULT NULL,
`AddressLine01` varchar(45) DEFAULT NULL,
`AddressLine02` varchar(45) DEFAULT NULL,
`City` varchar(45) DEFAULT NULL,
`State` varchar(45) DEFAULT NULL,
`ZipCode` varchar(10) DEFAULT NULL,
`Phone` varchar(13) DEFAULT NULL,
`Manufacturercol` varchar(45) DEFAULT NULL,
PRIMARY KEY (`ManufacturerID`),
UNIQUE KEY `Manufacturer_UNIQUE` (`Manufacturer`));
INSERT INTO product.manufacturer (Manufacturer) VALUES('Smuckers');
INSERT INTO product.manufacturer (Manufacturer) VALUES('Dannon');
INSERT INTO product.manufacturer (Manufacturer) VALUES('Kellogs');
INSERT INTO product.manufacturer (Manufacturer) VALUES('Pepsi');
CREATE TABLE `product`.`unit` (
`UnitID` INT NOT NULL AUTO_INCREMENT,
`Unit` VARCHAR(45) NOT NULL,
PRIMARY KEY (`UnitID`),
UNIQUE INDEX `Unit_UNIQUE` (`Unit` ASC));
INSERT INTO product.unit(Unit) VALUES('Box');
INSERT INTO product.unit(Unit) VALUES('Bag');
INSERT INTO product.unit(Unit) VALUES('Carton');
INSERT INTO product.unit(Unit) VALUES('Jar');
INSERT INTO product.unit(Unit) VALUES('Tube');
INSERT INTO product.unit(Unit) VALUES('Case');
INSERT INTO product.unit(Unit) VALUES('Cup');
CREATE TABLE `product`.`product` (
`ProductID` int(11) NOT NULL AUTO_INCREMENT,
`SKU` varchar(45) NOT NULL,
`Description` varchar(45) NOT NULL,
`ManufacturerID` int(11) NOT NULL,
`UnitCost` decimal(10,3) DEFAULT '0.000',
`UnitPrice` decimal(10,3) DEFAULT '0.000',
`UnitID` int(11) DEFAULT NULL,
PRIMARY KEY (`ProductID`),
UNIQUE KEY `SKU_UNIQUE` (`SKU`),
UNIQUE KEY `Description_UNIQUE` (`Description`),
KEY `ManufacturerID_idx` (`ManufacturerID`),
KEY `UnitID_idx` (`UnitID`),
CONSTRAINT `ManufacturerID` FOREIGN KEY (`ManufacturerID`) REFERENCES `manufacturer` (`ManufacturerID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `UnitID` FOREIGN KEY (`UnitID`) REFERENCES `unit` (`UnitID`) ON DELETE NO ACTION ON UPDATE NO ACTION
);
INSERT INTO product.product (SKU, Description, ManufacturerID, UnitCost, UnitPrice, UnitID) VALUES('P000000001', 'Blueberry Jam', 1, .50, 1.00, 4);
INSERT INTO product.product (SKU, Description, ManufacturerID, UnitCost, UnitPrice, UnitID) VALUES('P000000002', 'Coffee Yogurt', 2, 1.00, 2.00, 7);
INSERT INTO product.product (SKU, Description, ManufacturerID, UnitCost, UnitPrice, UnitID) VALUES('P000000003', '12 Individual Boxes Corn Flakes', 3, 1.00, 5.00, 6);
INSERT INTO product.product (SKU, Description, ManufacturerID, UnitCost, UnitPrice, UnitID) VALUES('P000000004', 'Box Corn Flakes', 3, 1.00, 5.00, 1);
END;
-- *********************
-- Loyalty (Customers)
-- *********************
BEGIN
DROP schema if exists `loyalty`;
END;
BEGIN
CREATE SCHEMA `loyalty`;
CREATE TABLE `loyalty`.`loyalty` (
`LoyaltyID` INT NOT NULL AUTO_INCREMENT,
`LoyaltyNumber` VARCHAR(10) NOT NULL,
`LastName` VARCHAR(45) NULL,
`FirstName` VARCHAR(45) NULL,
`AddressLine1` VARCHAR(45) NULL,
`AddressLine2` VARCHAR(45) NULL,
`City` VARCHAR(45) NULL,
`State` VARCHAR(2) NULL,
`ZipCode` INT NULL,
PRIMARY KEY (`LoyaltyID`),
UNIQUE INDEX `LoyaltyNumber_UNIQUE` (`LoyaltyNumber` ASC));
INSERT INTO loyalty.loyalty (LoyaltyID, LoyaltyNumber, LastName) VALUES(1, 'L000000001', 'Smith');
INSERT INTO loyalty.loyalty (LoyaltyID, LoyaltyNumber) VALUES(2, 'L000000002');
INSERT INTO loyalty.loyalty (LoyaltyID, LoyaltyNumber) VALUES(3, 'L000000003');
INSERT INTO loyalty.loyalty (LoyaltyID, LoyaltyNumber, LastName, FirstName) VALUES(4, 'L000000004', 'Knight', 'Robert');
END;
-- *********************
-- Reconciled Schema
-- *********************
BEGIN
DROP Schema if exists `reconciled`;
END;
BEGIN
CREATE SCHEMA `reconciled` ;
CREATE TABLE `reconciled`.`sale` (
`saleID` int(11) NOT NULL AUTO_INCREMENT,
`EmployeeFirstName` varchar(45) DEFAULT NULL,
`EmployeeLastName` varchar(45) DEFAULT NULL,
`ProductDescription` varchar(45) DEFAULT NULL,
`Unit` varchar(45) DEFAULT NULL,
`SKU` varchar(45) DEFAULT NULL,
`Qty` int(11) DEFAULT NULL,
`UnitCost` decimal(10,3) DEFAULT NULL,
`UnitPrice` decimal(10,3) DEFAULT NULL,
`Manufacturer` varchar(45) DEFAULT NULL,
`EmployeeNumber` varchar(45) DEFAULT NULL COMMENT 'The employee who handled the transaction',
`LoyaltyNumber` varchar(45) DEFAULT NULL,
`StoreNumber` varchar(45) DEFAULT NULL,
`DateOfTransaction` date DEFAULT NULL,
`TimeOfTransaction` time DEFAULT NULL,
`DateOfTransactionString` varchar(45) DEFAULT NULL,
`TimeOfTransactionString` varchar(45) DEFAULT NULL,
`WeekdayOfTransaction` int(11) DEFAULT NULL,
`MonthOfTransaction` int(11) DEFAULT NULL,
`YearOfTransaction` int(11) DEFAULT NULL,
`WeekdayNameOfTransaction` varchar(45) DEFAULT NULL,
`MonthNameOfTransaction` varchar(45) DEFAULT NULL,
`TotalPrice` decimal(10,3) DEFAULT NULL,
`ZipCode` varchar(10) DEFAULT NULL,
PRIMARY KEY (`saleID`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
CREATE TABLE `reconciled`.`weather` (
`WeatherID` int(11) NOT NULL AUTO_INCREMENT,
`DateStamp` date DEFAULT NULL,
`ZipCode` varchar(10) DEFAULT NULL,
`Temperature` int(11) DEFAULT NULL,
`MonthName` varchar(45) DEFAULT NULL,
`YearNumber` int(11) DEFAULT NULL,
`DayName` varchar(45) DEFAULT NULL,
`MonthNumber` int(11) DEFAULT NULL,
`DayNumber` int(11) DEFAULT NULL,
PRIMARY KEY (`WeatherID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
END;
-- *********************
-- Aggregated schema for the data warehouse
-- *********************
BEGIN
DROP Schema if exists dw;
CREATE SCHEMA `dw` ;
CREATE TABLE `dw`.`salesqtybyproductandstore` (
`SalesByProductAndStoreID` int(11) NOT NULL AUTO_INCREMENT,
`SKU` varchar(45) NOT NULL,
`StoreNumber` varchar(45) NOT NULL,
`ProductDescription` varchar(45) DEFAULT NULL,
`Monday` int(11) DEFAULT '0',
`Tuesday` int(11) DEFAULT '0',
`Wednesday` int(11) DEFAULT '0',
`Thursday` int(11) DEFAULT '0',
`Friday` int(11) DEFAULT '0',
`Saturday` int(11) DEFAULT '0',
`Sunday` int(11) DEFAULT '0',
PRIMARY KEY (`SalesByProductAndStoreID`),
UNIQUE KEY `SKU_UNIQUE` (`SKU`,`StoreNumber`)
);
END;
BEGIN
CREATE TABLE `dw`.`monthlysalesqtybyproductandstore` (
`monthlysalesqtybyproductandstoreID` int(11) NOT NULL AUTO_INCREMENT,
`SKU` varchar(45) NOT NULL,
`StoreNumber` varchar(45) NOT NULL,
`ProductDescription` varchar(45) DEFAULT NULL,
`January` int(11) DEFAULT '0',
`February` int(11) DEFAULT '0',
`March` int(11) DEFAULT '0',
`April` int(11) DEFAULT '0',
`May` int(11) DEFAULT '0',
`June` int(11) DEFAULT '0',
`July` int(11) DEFAULT '0',
`August` int(11) DEFAULT '0',
`September` int(11) DEFAULT '0',
`October` int(11) DEFAULT '0',
`November` int(11) DEFAULT '0',
`December` int(11) DEFAULT '0',
PRIMARY KEY (`monthlysalesqtybyproductandstoreID`),
UNIQUE KEY `SKU_UNIQUE` (`SKU`,`StoreNumber`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
CREATE TABLE `dw`.`weeklysalesqtybyproductandstore` (
`WeeklysalesqtybyproductandstoreID` int(11) NOT NULL AUTO_INCREMENT,
`SKU` varchar(45) NOT NULL,
`StoreNumber` varchar(45) NOT NULL,
`ProductDescription` varchar(45) DEFAULT NULL,
`Monday` int(11) DEFAULT '0',
`Tuesday` int(11) DEFAULT '0',
`Wednesday` int(11) DEFAULT '0',
`Thursday` int(11) DEFAULT '0',
`Friday` int(11) DEFAULT '0',
`Saturday` int(11) DEFAULT '0',
`Sunday` int(11) DEFAULT '0',
PRIMARY KEY (`WeeklysalesqtybyproductandstoreID`),
UNIQUE KEY `SKU_UNIQUE` (`SKU`,`StoreNumber`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
CREATE TABLE `dw`.`storesalesbytemperature` (
`StoreSalesByTemperatureID` INT NOT NULL AUTO_INCREMENT,
`StoreNumber` VARCHAR(45) NULL,
`Under0` DECIMAL(10,2) NULL,
`0To20` DECIMAL(10,2) NULL,
`21To30` DECIMAL(10,2) NULL,
`31To40` DECIMAL(10,2) NULL,
`41To50` DECIMAL(10,2) NULL,
`51To60` DECIMAL(10,2) NULL,
`61To70` DECIMAL(10,2) NULL,
`71To80` DECIMAL(10,2) NULL,
`81To90` DECIMAL(10,2) NULL,
`Over90` DECIMAL(10,2) NULL,
`StoreSalesByTemperaturecol` VARCHAR(45) NULL,
PRIMARY KEY (`StoreSalesByTemperatureID`),
INDEX `Unique` (`StoreNumber` ASC));
END;
BEGIN
DROP Schema if exists icecream;
CREATE SCHEMA `icecream`;
CREATE TABLE `icecream`.`flavor` (
`FlavorID` INT NOT NULL AUTO_INCREMENT,
`Flavor` VARCHAR(45) NULL,
PRIMARY KEY (`FlavorID`),
UNIQUE INDEX `Flavor_UNIQUE` (`Flavor` ASC));
CREATE TABLE `icecream`.`container` (
`ContainerID` INT NOT NULL AUTO_INCREMENT,
`Container` VARCHAR(45) NULL,
PRIMARY KEY (`ContainerID`),
UNIQUE INDEX `Container_UNIQUE` (`Container` ASC));
CREATE TABLE `icecream`.`icecream` (
`IceCreamID` int(11) NOT NULL AUTO_INCREMENT,
`FlavorID` int(11) DEFAULT NULL,
`ContainerID` int(11) DEFAULT NULL,
`SKU` varchar(45) DEFAULT NULL,
PRIMARY KEY (`IceCreamID`),
UNIQUE KEY `Unique` (`ContainerID`,`FlavorID`),
UNIQUE KEY `SKU_UNIQUE` (`SKU`),
CONSTRAINT `Container` FOREIGN KEY (`ContainerID`) REFERENCES `icecream`.`container` (`ContainerID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `Flavor` FOREIGN KEY (`FlavorID`) REFERENCES `icecream`.`flavor` (`FlavorID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO icecream.flavor (flavor) VALUES('Chocolate');
INSERT INTO icecream.flavor (flavor) VALUES('Vanilla');
INSERT INTO icecream.flavor (flavor) VALUES('Strawberry');
INSERT INTO icecream.flavor (flavor) VALUES('Raspberry Chocolate Chip');
INSERT INTO icecream.flavor (flavor) VALUES('Blueberry');
INSERT INTO icecream.container (Container) VALUES('cup');
INSERT INTO icecream.container (Container) VALUES('pint');
INSERT INTO icecream.container (Container) VALUES('quart');
INSERT INTO icecream.container (Container) VALUES('half gallon');
INSERT INTO icecream.container (Container) VALUES('gallon');
INSERT INTO icecream.icecream (flavorID, containerID, SKU) VALUES(1, 2, 'I000000001');
INSERT INTO icecream.icecream (flavorID, containerID, SKU) VALUES(2, 2, 'I000000002');
INSERT INTO icecream.icecream (flavorID, containerID, SKU) VALUES(3, 2, 'I000000003');
INSERT INTO icecream.icecream (flavorID, containerID, SKU) VALUES(1, 3, 'I000000004');
INSERT INTO icecream.icecream (flavorID, containerID, SKU) VALUES(2, 3, 'I000000005');
INSERT INTO icecream.icecream (flavorID, containerID, SKU) VALUES(3, 3, 'I000000006');
INSERT INTO icecream.icecream (flavorID, containerID) VALUES(4, 1);
END;
-- *********************
-- Schema Sales
-- *********************
BEGIN
DROP Schema if exists `weather`;
END;
BEGIN
CREATE SCHEMA `weather` ;
CREATE TABLE `weather`.`weather` (
`weatherText` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO weather.weather (weatherText) VALUES('2018/01/01 00:00:00.0000,45255,10');
INSERT INTO weather.weather (weatherText) VALUES('2018/01/02 00:00:00.0000,45255,12');
INSERT INTO weather.weather (weatherText) VALUES('2018/01/03 00:00:00.0000,45255,14');
INSERT INTO weather.weather (weatherText) VALUES('2018/01/04 00:00:00.0000,45255,16');
INSERT INTO weather.weather (weatherText) VALUES('2018/01/01 00:00:00.0000,45103,15');
INSERT INTO weather.weather (weatherText) VALUES('2018/01/02 00:00:00.0000,45103,17');
INSERT INTO weather.weather (weatherText) VALUES('2018/01/03 00:00:00.0000,45103,19');
INSERT INTO weather.weather (weatherText) VALUES('2018/01/04 00:00:00.0000,45103,21');
END;
-- *********************
-- Schema Sales
-- *********************
BEGIN
DROP Schema if exists `sales`;
END;
BEGIN
CREATE SCHEMA `sales` ;
CREATE TABLE `sales`.`transaction` (
`TransactionID` int(11) NOT NULL AUTO_INCREMENT,
`DateTimeOfTransaction` datetime NOT NULL,
`LoyaltyNumber` varchar(10) DEFAULT NULL,
`StoreNumber` varchar(10) NOT NULL,
`EmployeeNumber` varchar(10) NOT NULL,
PRIMARY KEY (`TransactionID`),
UNIQUE KEY `NaturalKey` (`DateTimeOfTransaction`,`LoyaltyNumber`,`StoreNumber`,`EmployeeNumber`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
END;
BEGIN
INSERT INTO `sales`.`transaction` (TransactionID, DateTimeOfTransaction, LoyaltyNumber, StoreNumber, EmployeeNumber) VALUES(1, '2018-01-01 15:00:00', 'L000000001', 'S000000001', 'E000000001');
INSERT INTO `sales`.`transaction` (TransactionID, DateTimeOfTransaction, LoyaltyNumber, StoreNumber, EmployeeNumber) VALUES(2, '2018-02-02 15:00:00', 'L000000002', 'S000000002', 'E000000002');
INSERT INTO `sales`.`transaction` (TransactionID, DateTimeOfTransaction, LoyaltyNumber, StoreNumber, EmployeeNumber) VALUES(3, '2018-02-07 16:00:00', 'L000000002', 'S000000002', 'E000000002');
INSERT INTO `sales`.`transaction` (TransactionID, DateTimeOfTransaction, LoyaltyNumber, StoreNumber, EmployeeNumber) VALUES(4, '2018-02-09 16:16:00', 'L000000002', 'S000000002', 'E000000002');
END;
BEGIN
-- YYYY-MM-DD HH:MM:SS
CREATE TABLE `sales`.`transactiondetail` (
`TransactionDetailID` int(11) NOT NULL AUTO_INCREMENT,
`TransactionID` int(11) NOT NULL,
`SKU` varchar(45) NOT NULL,
`Qty` int(11) NOT NULL,
`TotalPrice` decimal(10,3) NOT NULL,
`Comment` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`TransactionDetailID`),
UNIQUE KEY `NaturalKey` (`TransactionID`,`SKU`),
KEY `TransactionID_idx` (`TransactionID`),
CONSTRAINT `TransactionID` FOREIGN KEY (`TransactionID`) REFERENCES `sales`.`transaction` (`TransactionID`) ON DELETE NO ACTION ON UPDATE NO ACTION);
END;
BEGIN
INSERT INTO sales.transactiondetail (TransactionID, SKU, Qty, TotalPrice) VALUES(1, 'P000000001', 10, 100);
INSERT INTO sales.transactiondetail (TransactionID, SKU, Qty, TotalPrice) VALUES(1, 'P000000002', 5, 25);
INSERT INTO sales.transactiondetail (TransactionID, SKU, Qty, TotalPrice) VALUES(2, 'P000000001', 1, 100);
INSERT INTO sales.transactiondetail (TransactionID, SKU, Qty, TotalPrice) VALUES(2, 'P000000002', 2, 25);
INSERT INTO sales.transactiondetail (TransactionID, SKU, Qty, TotalPrice) VALUES(3, 'P000000002', 40, 40);
INSERT INTO sales.transactiondetail (TransactionID, SKU, Qty, TotalPrice) VALUES(4, 'P000000002', 44, 44);
END;
BEGIN
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`#`localhost`
SQL SECURITY DEFINER
VIEW `reconciled`.`mapping` AS
SELECT
`hr`.`employee`.`FirstName` AS `EmployeeFirstName`,
`hr`.`employee`.`LastName` AS `EmployeeLastName`,
`product`.`product`.`Description` AS `ProductDescription`,
`product`.`unit`.`Unit` AS `Unit`,
`product`.`product`.`SKU` AS `SKU`,
`sales`.`transactiondetail`.`Qty` AS `Qty`,
`product`.`product`.`UnitCost` AS `UnitCost`,
`product`.`product`.`UnitPrice` AS `UnitPrice`,
`product`.`manufacturer`.`Manufacturer` AS `Manufacturer`,
`sales`.`transaction`.`EmployeeNumber` AS `EmployeeNumber`,
`sales`.`transaction`.`LoyaltyNumber` AS `LoyaltyNumber`,
`sales`.`transaction`.`StoreNumber` AS `StoreNumber`,
`store`.`store`.`zipCode` as `ZipCode`,
CAST(`sales`.`transaction`.`DateTimeOfTransaction`
AS DATE) AS `DateOfTransaction`,
CAST(`sales`.`transaction`.`DateTimeOfTransaction`
AS TIME) AS `TimeOfTransaction`,
CAST(CAST(`sales`.`transaction`.`DateTimeOfTransaction`
AS DATE)
AS CHAR CHARSET UTF8) AS `DateOfTransactionString`,
CAST(CAST(`sales`.`transaction`.`DateTimeOfTransaction`
AS TIME)
AS CHAR CHARSET UTF8) AS `TimeOfTransactionString`,
WEEKDAY(`sales`.`transaction`.`DateTimeOfTransaction`) AS `WeekdayOfTransaction`,
MONTH(`sales`.`transaction`.`DateTimeOfTransaction`) AS `MonthOfTransaction`,
YEAR(`sales`.`transaction`.`DateTimeOfTransaction`) AS `YearOfTransaction`,
DAYNAME(`sales`.`transaction`.`DateTimeOfTransaction`) AS `WeekdayNameOfTransaction`,
MONTHNAME(`sales`.`transaction`.`DateTimeOfTransaction`) AS `MonthNameOfTransaction`,
`sales`.`transactiondetail`.`TotalPrice` AS `TotalPrice`
FROM
((((((`sales`.`transaction`
JOIN `sales`.`transactiondetail` ON ((`sales`.`transaction`.`TransactionID` = `sales`.`transactiondetail`.`TransactionID`)))
JOIN `hr`.`employee` ON ((`hr`.`employee`.`EmployeeNumber` = `sales`.`transaction`.`EmployeeNumber`)))
JOIN `product`.`product` ON ((`product`.`product`.`SKU` = `sales`.`transactiondetail`.`SKU`)))
JOIN `product`.`unit` ON ((`product`.`product`.`UnitID` = `product`.`unit`.`UnitID`)))
JOIN `store`.`store` ON ((`store`.`store`.`StoreNumber` = `sales`.`transaction`.`StoreNumber`)))
JOIN `product`.`manufacturer` ON ((`product`.`product`.`ManufacturerID` = `product`.`manufacturer`.`ManufacturerID`))) ;
CREATE TABLE `reconciled`.`icecream` (
`icecreamid` int(11) NOT NULL AUTO_INCREMENT,
`flavor` varchar(45) DEFAULT NULL,
`container` varchar(45) DEFAULT NULL,
`sku` varchar(45) DEFAULT NULL,
PRIMARY KEY (`icecreamid`),
UNIQUE KEY `Unique` (`flavor`,`container`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
END;
BEGIN
CREATE VIEW `reconciled`.`totalSalesByStoreAndTemperature` AS
SELECT StoreNumber, temperature, SUM(TotalPrice) as `SumOfTotalPrice`
FROM reconciled.sale inner join reconciled.weather on Substring(reconciled.sale.zipCode,1,5) = substring(reconciled.weather.zipCode,1,5)
Group By StoreNumber, temperature
ORDER BY StoreNumber, Temperature;
END;
END
Just want to add the root cause of this issue.
Cloud SQL currently is limited to grant SUPER and FILE privileges according to GCP documentation, so they can't be assigned to any user including root.
As per MySQL 5.7 documentation, the DEFINER attribute requires the user to have the SUPER privilege.
The situation above was the cause of your error and it worked when you took out the DEFINER statement.
In summary any other action that requires SUPER o FILE privileges most probably will fail with the error "Access denied; you need (at least one of) the SUPER privilege(s) for this operation".
I took out the DEFINER clause in the creation of the view reconciled.mapping.
That eliminated the error when I executed the SP.
It wasn't the DEFINER clause of the SP creation script, it was the DEFINER clause in the SP itself.
with my experience in AWS RDS, you don't get SUPER privileges as those are used by the provisioner engine. I am pretty sure that is how it is done in GCP. It could be that something in query make MySQL think it needs SUPER privileges. Posting your query which is giving the error will be helpful.
-------Update after OP posted the query----------
this is the problem. DEFINER. try CREATE PROCEDURE CreateFullCoverageTestCase()

selecting multiple rows issue in mysql

I am beginner in sql.
I have two tables users and installments
CREATE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) NOT NULL,
`password` varchar(10) NOT NULL,
`father_name` varchar(20) NOT NULL,
`phone` varchar(20) NOT NULL,
`cnic` varchar(20) NOT NULL,
`email` varchar(100) NOT NULL,
`address` varchar(100) NOT NULL,
`introducer` varchar(100) NOT NULL,
`date` date DEFAULT NULL,
`reg_number` varchar(100) DEFAULT NULL,
`installment` int(100) NOT NULL,
`user_level` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `cnic` (`cnic`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `users` (`id`, `user_name`, `password`, `father_name`, `phone`, `cnic`, `email`, `address`, `introducer`, `date`, `reg_number`, `installment`, `user_level`) VALUES
(2, 'qaser', 'Qaser1', 'zamarrud', '0312546879', '37406-3140185-1', 'tariq_kareem#yahoo.com', 'street # 6', 'rizwan', '2014-08-20', 'E-002', 3000, 0);
and
CREATE `installments` (
`installment_id` int(11) NOT NULL AUTO_INCREMENT,
`month` date DEFAULT NULL,
`prv_arrear` int(100) NOT NULL,
`amount` int(100) NOT NULL,
`total` int(100) NOT NULL,
`receive` int(100) NOT NULL,
`arrear` int(100) NOT NULL,
`fk_users_id` int(11) NOT NULL,
PRIMARY KEY (`installment_id`),
KEY `fk_users_id` (`fk_users_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
INSERT INTO `installments` (`installment_id`, `month`, `prv_arrear`, `amount`, `total`, `receive`, `arrear`) VALUES
(2, '2014-08-20', 2000, 2500, 4500, 3000, 1500);
when I run the following query I get the first table's record correctly but the second table's record showing NULL values
SELECT * FROM users
LEFT JOIN installments
ON users.id=installments.installment_id
WHERE users.cnic='37406-3140185-1';
Is there anything missing in the above query or is there another way to get the record from both tables simultaneously
id user_name password father_name phone cnic email address introducer date reg_number installment user_level installment_id month prv_arrear amount total receive arrear fk_users_id
2 qaser Qaser1 zamarrud 0312546879 37406-3140185-1 tariq_kareem#yahoo.com street # 6 rizwan 2014-08-20 s-001 3000 0 NULL NULL NULL NULL NULL NULL NULL NULL
I am also using the following query to inserting the record for getting primary key value and insert into foreign key
INSERT INTO `installments`(`id`, `month`, `prv_arrear`, `amount`, `total`, `receive`, `arrear`, fk_users_id)
SELECT NULL,now(),1000,2500,3500,3000,500, id
FROM users
WHERE cnic = '37406-3140190-1'
please help me thanks in advance and sorry if there is something wrong in my question because I am new in sql.
I suspect the right join condition is on fk_users_id. So this might do what you want:
SELECT *
FROM users u LEFT JOIN
installments i
ON u.id = i.fk_users_id
WHERE u.cnic = '37406-3140185-1';

How to calculate sum of two columns from two different tables without where clause?

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