Mysql join multiple tables with one select phrase - mysql

http://sqlfiddle.com/#!9/708aef/8/0
I have an table called mmsusbribers where i store information from users.
Then i have 3 other tables: driftinfo_subscriber_operator_lookup, driftinfo_subscriber_reseller_lookup and driftinfo_subscriber_server_lookup.
I want to join the tables together all of them in one select.
Tables look like this:
CREATE TABLE IF NOT EXISTS `mmsubscribers` (
`id` int(11) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`name` varchar(50) DEFAULT NULL,
`hash` varchar(100) DEFAULT NULL,
`status` varchar(50) DEFAULT NULL,
`listid` int(11) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`login` varchar(50) DEFAULT NULL,
`pass` varchar(50) DEFAULT NULL,
`language` varchar(50) DEFAULT NULL,
`orgname` varchar(75) DEFAULT NULL,
`orgadmin` int(11) DEFAULT NULL,
`domain` varchar(150) DEFAULT NULL,
`organizationId` int(11) DEFAULT NULL,
`number` varchar(15) DEFAULT NULL,
`department` varchar(50) DEFAULT NULL,
`server` varchar(20) DEFAULT NULL,
`reseller` varchar(75) DEFAULT NULL,
`operators` varchar(50) DEFAULT NULL,
`subscriber_type` int(11) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=166629 DEFAULT CHARSET=utf8;
INSERT INTO `mmsubscribers` (`id`, `email`, `name`, `hash`, `status`,
`listid`, `phone`, `login`, `pass`, `language`, `orgname`, `orgadmin`,
`domain`, `organizationId`, `number`, `department`, `server`, `reseller`,
`operators`, `subscriber_type`) VALUES
(13, 'nils#gmail.com', 'Nils Nissesson', NULL, 'inactive', 2, '+4612312313',
'user1', 'user1', 'SV', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'Reseller1',
NULL, NULL),
(15, 'nils#hotmail.com', 'Nils Karlsson', 'b5q8gelmyvp4gu9sgntgvzkha0u', 'active', 2, '+47741741109874', NULL, NULL, 'EN', '', NULL, NULL, NULL, NULL, NULL, '', '', '', NULL),
(17, 'test#testing.com', 'Test Karlsson', 'mdpte4uhkvqzew4n2megoa4qk7k', 'active', 2, '+4482798273798', NULL, NULL, 'SV', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL),
(18, 'test123#testdomain.se', 'Herr Vincze', 'mhw81k96liwlfj8lkyvu2rdr9y', 'inactive', 2, '', NULL, NULL, 'SV', '', NULL, '', NULL, '', '', '', '', '', NULL),
(146996, 'nils.nils#nils.se', 'Nils Dolk', 'dd07c78e2fa7487b283f6c4dbff7ec0fc448a4', 'active', 3, '', NULL, NULL, '', 'Test', 1, 'nils.se', 6721, '468123123454', 'Sälj', '185.XX.124.162', 'Reseller56', 'STH-UNO', 4),
(149277, 'bo#bosse.com', 'Bo Holgersson', 'c557202473aef551d410a00d2b1be3075e8d7e1fe', 'active', 3, '', NULL, NULL, '', 'Test', 1, 'bo.se', 6578, '4653643232436', 'Företagsförsäljning', '185.39.124.154', 'Reseller1', 'STB-uno', 4),
(149824, 'support#nisse.no', 'testar', '9c5f161459236d5d216c48a47d0c2aecf1', 'active', 3, '', NULL, NULL, '', 'Test', 1, 'bo.se', 6578, '4654170399', '', '185.XX.124.162', 'Reseller1', 'Tele2', 4);
First table witch i want to do the join to:
CREATE TABLE IF NOT EXISTS `driftinfo_subscriber_operator_lookup` (
`id` int(11) NOT NULL,
`drifinfo_problem_id` int(11) DEFAULT NULL,
`operator` varchar(75) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
--
-- Dumpning av Data i tabell `driftinfo_subscriber_operator_lookup`
--
INSERT INTO `driftinfo_subscriber_operator_lookup` (`id`, `drifinfo_problem_id`, `operator`) VALUES
(1, 4, 'Weblink'),
(4, 10, 'Tele2');
Second table:
CREATE TABLE IF NOT EXISTS `driftinfo_subscriber_reseller_lookup` (
`id` int(11) NOT NULL,
`drifinfo_problem_id` int(11) DEFAULT NULL,
`reseller` varchar(75) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
--
-- Dumpning av Data i tabell `driftinfo_subscriber_reseller_lookup`
--
INSERT INTO `driftinfo_subscriber_reseller_lookup` (`id`, `drifinfo_problem_id`, `reseller`) VALUES
(1, 4, 'Reseller1'),
(2, 4, 'Reseller2'),
(5, 10, 'Reseller3'),
(6, 10, 'BestReseller'),
(7, 10, 'BadReseller');
Third table:
CREATE TABLE IF NOT EXISTS `driftinfo_subscriber_server_lookup` (
`id` int(11) NOT NULL,
`drifinfo_problem_id` int(11) DEFAULT NULL,
`server` varchar(50) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
--
-- Dumpning av Data i tabell `driftinfo_subscriber_server_lookup`
--
INSERT INTO `driftinfo_subscriber_server_lookup` (`id`, `drifinfo_problem_id`, `server`) VALUES
(1, 4, '185.XX.124.162'),
(8, 10, '172.XX.129.20'),
(9, 10, '172.XX.129.21');
My last table:
CREATE TABLE IF NOT EXISTS `driftinfo_problem` (
`id` int(11) NOT NULL,
`active` varchar(11) DEFAULT NULL,
`date` date DEFAULT NULL,
`omrade` varchar(75) DEFAULT NULL,
`soluno_staging_message` varchar(750) DEFAULT NULL,
`heading` varchar(100) DEFAULT NULL,
`ingress` varchar(750) DEFAULT NULL,
`image` varchar(1500) DEFAULT NULL,
`text` varchar(3000) DEFAULT NULL,
`beskrivning` varchar(250) DEFAULT NULL,
`user_owner` varchar(75) DEFAULT NULL,
`estimate_finished_date` date DEFAULT NULL,
`language` varchar(50) DEFAULT NULL,
`time` time DEFAULT NULL,
`estimate_finished_time` time DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
--
-- Dumpning av Data i tabell `driftinfo_problem`
--
INSERT INTO `driftinfo_problem` (`id`, `active`, `date`, `omrade`, `soluno_staging_message`, `heading`, `ingress`, `image`, `text`, `beskrivning`, `user_owner`, `estimate_finished_date`, `language`, `time`, `estimate_finished_time`) VALUES
(2, 'No', '2018-04-18', 'Test Problem', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-04-18', NULL, '09:04:00', '16:00:00'),
(3, 'No', '2018-04-27', 'Operatör tysta samtal', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-04-27', NULL, '11:35:00', '14:30:00'),
(4, 'No', '2018-05-16', 'Operator driftstörning', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-16', NULL, '11:20:00', '14:00:00'),
(5, 'No', '2018-05-17', 'Operator driftstörning', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-17', NULL, '14:30:00', '17:00:00'),
(6, 'No', '2018-05-18', 'Internet problem', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-18', NULL, '16:00:00', '18:00:00'),
(7, 'No', '2018-05-25', 'Operator driftstörning', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-25', NULL, '14:30:00', '17:00:00'),
(8, 'No', '2018-05-28', 'Operator routing problem', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-29', NULL, '16:00:00', '12:00:00'),
(10, 'Yes', '2018-05-31', 'Operator Business störning', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-31', NULL, '10:00:00', '14:00:00');
SQL Fiddle
I need to do an combination of these 3 selects into 1 select if possible.
Select1 operator:
SELECT
mmsubscribers.email,
driftinfo_problem.active,
driftinfo_problem.id,
mmsubscribers.reseller,
mmsubscribers.operators,
mmsubscribers.server
FROM mmsubscribers
INNER JOIN driftinfo_subscriber_operator_lookup ON mmsubscribers.operators = driftinfo_subscriber_operator_lookup.`operator`
INNER JOIN driftinfo_problem ON driftinfo_subscriber_operator_lookup.drifinfo_problem_id = driftinfo_problem.id
WHERE driftinfo_problem.active = 'Yes'
Select2 reseller:
SELECT
mmsubscribers.email,
driftinfo_problem.active,
driftinfo_problem.id,
mmsubscribers.reseller,
mmsubscribers.operators,
mmsubscribers.server
FROM mmsubscribers
INNER JOIN driftinfo_subscriber_reseller_lookup ON mmsubscribers.reseller = driftinfo_subscriber_reseller_lookup.reseller
INNER JOIN driftinfo_problem ON driftinfo_subscriber_reseller_lookup.drifinfo_problem_id = driftinfo_problem.id
Select3 server:
SELECT
mmsubscribers.email,
driftinfo_problem.active,
driftinfo_problem.id,
mmsubscribers.reseller,
mmsubscribers.operators,
mmsubscribers.server
FROM mmsubscribers
INNER JOIN driftinfo_subscriber_server_lookup ON mmsubscribers.server = driftinfo_subscriber_server_lookup.server
INNER JOIN driftinfo_problem ON driftinfo_subscriber_server_lookup.drifinfo_problem_id = driftinfo_problem.id
Expected output that i woul like to get is:
email active id reseller operators server
nils#gmail.com No 4 Reseller1 (null) (null)
bo#bosse.com No 4 Reseller1 STB-uno 185.39.124.154
support#nisse.no No 4 Reseller1 Tele2 185.XX.124.162
nils.nils#nils.se No 4 Reseller56 STH-UNO 185.XX.124.162
support#nisse.no No 4 Reseller1 Tele2 185.XX.124.162
support#nisse.no Yes 10 Reseller1 Tele2 185.XX.124.162

SELECT
mmsubscribers.email,
driftinfo_problem.active,
driftinfo_problem.id,
mmsubscribers.reseller,
mmsubscribers.operators,
mmsubscribers.server
FROM mmsubscribers
INNER JOIN driftinfo_subscriber_operator_lookup ON mmsubscribers.operators = driftinfo_subscriber_operator_lookup.`operator`
INNER JOIN driftinfo_problem ON driftinfo_subscriber_operator_lookup.drifinfo_problem_id = driftinfo_problem.id
WHERE driftinfo_problem.active = 'Yes'
union all
SELECT
mmsubscribers.email,
driftinfo_problem.active,
driftinfo_problem.id,
mmsubscribers.reseller,
mmsubscribers.operators,
mmsubscribers.server
FROM mmsubscribers
INNER JOIN driftinfo_subscriber_reseller_lookup ON mmsubscribers.reseller = driftinfo_subscriber_reseller_lookup.reseller
INNER JOIN driftinfo_problem ON driftinfo_subscriber_reseller_lookup.drifinfo_problem_id = driftinfo_problem.id
union all
SELECT
mmsubscribers.email,
driftinfo_problem.active,
driftinfo_problem.id,
mmsubscribers.reseller,
mmsubscribers.operators,
mmsubscribers.server
FROM mmsubscribers
INNER JOIN driftinfo_subscriber_server_lookup ON mmsubscribers.server = driftinfo_subscriber_server_lookup.server
INNER JOIN driftinfo_problem ON driftinfo_subscriber_server_lookup.drifinfo_problem_id = driftinfo_problem.id;

Related

Select subscriptions based on user id

I have these MySQL tables where I want to store user subscriptions:
CREATE TABLE subscription (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` decimal(19,2) DEFAULT NULL,
`created_at` datetime(6) DEFAULT NULL,
`currency` varchar(20) DEFAULT NULL,
`duration` bigint(20) DEFAULT NULL,
`end_at` datetime(6) DEFAULT NULL,
`error` varchar(200) DEFAULT NULL,
`order_id` int(11) DEFAULT NULL,
`product` varchar(20) DEFAULT NULL,
`run_at` datetime(6) DEFAULT NULL,
`start_at` datetime(6) DEFAULT NULL,
`status` varchar(20) DEFAULT NULL,
`updated_at` datetime(6) DEFAULT NULL,
`title` varchar(20) DEFAULT NULL,
`parent_transaction_id` int(11) DEFAULT NULL,
`parent_transactionId` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23443556 DEFAULT CHARSET=latin1;
INSERT INTO subscription (`id`, `amount`, `created_at`, `currency`, `duration`, `end_at`, `error`, `order_id`, `product`, `run_at`, `start_at`, `status`, `updated_at`, `title`, `parent_transaction_id`, `parent_transactionId`) VALUES
('122', '3333.00', '2020-10-31 19:41:16.622386', 'USD', '1000', '2020-10-31 19:41:16.622386', 'error message', '122', 'error message', '2020-10-31 19:41:16.622386', '2020-10-31 19:41:16.622386', 'active', '2020-10-31 19:41:16.622386', 'title', '443', '5544');
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
`enabled` tinyint(4) DEFAULT NULL,
`encrypted_password` varchar(255) DEFAULT NULL,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`role` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=153 DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `email`, `enabled`, `encrypted_password`, `first_name`, `last_name`, `role`) VALUES
('192', 'test#mail.com', '1', '$2a$31$ovShEKleI3Yk2vgjAIF5mO4HkGWXcTSKPMTaj7rFN4KAtlEz0f/ay', 'test', 'test', 'ROLE_CLIENT');
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`city` varchar(30) DEFAULT NULL,
`CONTENT` text DEFAULT NULL,
`country` varchar(50) DEFAULT NULL,
`created_at` datetime(6) DEFAULT NULL,
`discount` decimal(8,2) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`first_name` varchar(50) DEFAULT NULL,
`grand_total` decimal(8,2) DEFAULT NULL,
`item_discount` decimal(8,2) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
`line1` varchar(50) DEFAULT NULL,
`line2` varchar(50) DEFAULT NULL,
`middle_name` varchar(50) DEFAULT NULL,
`mobile` varchar(15) DEFAULT NULL,
`promo` varchar(100) DEFAULT NULL,
`province` varchar(50) DEFAULT NULL,
`session_id` int(11) DEFAULT NULL,
`shipping` decimal(8,2) DEFAULT NULL,
`status` varchar(100) DEFAULT NULL,
`sub_total` decimal(8,2) DEFAULT NULL,
`tax` decimal(8,2) DEFAULT NULL,
`token` varchar(100) DEFAULT NULL,
`total` decimal(8,2) DEFAULT NULL,
`updated_at` datetime(6) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=latin1;
INSERT INTO `orders` (`id`, `city`, `CONTENT`, `country`, `created_at`, `email`, `first_name`, `grand_total`, `item_discount`, `last_name`, `status`, `sub_total`, `tax`, `total`, `user_id`) VALUES
('122', 'city', 'test context', 'USA', '2021-05-25 12:40:23.793779', 'test#email.com', 'first name', '100', '10', 'last name', 'active', '20', '10', '200', '192');
INSERT INTO `orders` (`id`, `city`, `CONTENT`, `country`, `created_at`, `email`, `first_name`, `grand_total`, `item_discount`, `last_name`, `status`, `sub_total`, `tax`, `total`, `user_id`) VALUES
('124', 'city', 'test context', 'USA', '2021-05-25 12:40:23.793779', 'test#email.com', 'first name', '100', '10', 'last name', 'active', '20', '10', '200', '192');
CREATE TABLE `order_item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`discount` decimal(19,2) DEFAULT NULL,
`order_id` int(11) DEFAULT NULL,
`price` decimal(19,2) DEFAULT NULL,
`product_id` int(11) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
`sku` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SQLFiddle: http://sqlfiddle.com/#!9/1d6ba6/1
I use this SQL query with 2 JOINS to get the subsriptions:
SELECT *
FROM subscription
INNER JOIN Orders ON subscription.order_id = Orders.id AND subscription.id = 122
INNER JOIN users ON users.id = users.id AND Orders.user_id = 192
ORDER BY subscription.id;
As you can see I use 2 params in order to make 2 JOINS. Is it possible just to send the user id as a param and based from the match Orders.id AND subscription.id to get the subscription records that are found?
Your query didn't make sense, with ON Clause that links orders and user
So you can achieve the same result, without the user
SELECT *
FROM subscription
INNER JOIN Orders ON subscription.order_id = Orders.id AND subscription.id = 122
INNER JOIN users ON users.id = Orders.user_id
ORDER BY subscription.id;
btw the user of aliases can help keep more overview
SELECT *
FROM subscription s
INNER JOIN Orders o ON s.order_id = o.id AND s.id = 122
INNER JOIN users u ON u.id = o.user_id
ORDER BY s.id;

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

MySQL: Joining 3 tables doesn't return all results from 3rd Join

Goal: When given a user_id, retrieve the last 2 orders, with payment information, and all the items inside the order.
Query:
SELECT
PO.id,
PO.id AS order_id,
PO.user_id,
PO.deliveryaddress_id,
PO.delivery_type,
PO.store_id,
PO.placed_by,
PO.orderplaced_ts AS order_timestamp,
POP.subtotal AS order_subtotal,
POP.tax AS order_tax,
POP.secondary_tax AS order_secondary_tax,
POP.soda_tax AS order_soda_tax,
POP.delivery_fee AS order_delivery_fee,
POP.tip AS order_tip,
POP.discount AS order_discount,
POP.total AS order_total,
POP.payment_method,
POP.payment_details,
POM.*
FROM `orders` AS PO
JOIN `order_payments` AS POP
ON PO.id = POP.order_id
JOIN`order_items` AS POM
ON PO.id = POM.order_id
WHERE
PO.user_id = 12345
AND
PO.order_status != 'Cancelled'
AND
PO.order_status != 'Pending'
AND
POP.payment_collected = '1'
GROUP BY PO.id DESC
The result that I'm current receiving is only retrieving the first record from order_items table, which isn't correct. I'm attempting to retrieve ALL rows from order_items
Here is data set
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`deliveryaddress_id` int(11) NOT NULL,
`billingaddress_id` int(11) NOT NULL,
`delivery_type` enum('D','P') NOT NULL COMMENT 'D: Delivery; P: Pickup;',
`store_id` int(11) NOT NULL,
`placed_by` int(11) NOT NULL,
`ordercreated_ts` datetime NOT NULL,
`orderplaced_ts` datetime NOT NULL,
`orderread_ts` datetime NOT NULL,
`orderfulfilled_ts` datetime NOT NULL,
`order_status` enum('','Cancelled','Pending') NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5443062 DEFAULT CHARSET=latin1;
CREATE TABLE `order_payments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`order_id` int(11) NOT NULL,
`subtotal` decimal(9,2) NOT NULL,
`tax` decimal(9,2) NOT NULL,
`secondary_tax` decimal(9,2) NOT NULL,
`soda_tax` decimal(9,2) NOT NULL,
`delivery_fee` decimal(9,2) NOT NULL,
`tip` decimal(9,2) NOT NULL,
`discount` decimal(9,2) NOT NULL,
`total` decimal(9,2) NOT NULL,
`payment_method` enum('Level Up','Credit Card','Cash','House Account') NOT NULL,
`payment_details` varchar(150) DEFAULT NULL,
`payment_collected` enum('0','1') NOT NULL DEFAULT '0' COMMENT '0: payment not collected; 1: payment collected;',
PRIMARY KEY (`id`),
KEY `order_id` (`order_id`),
KEY `user_id` (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5277852 DEFAULT CHARSET=latin1;
CREATE TABLE `order_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL,
`menuitem_id` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`whofor` varchar(50) DEFAULT NULL,
`choppingpreference` varchar(50) DEFAULT NULL,
`in_a_wrap` varchar(50) DEFAULT NULL,
`dressingpreference` varchar(50) DEFAULT NULL,
`includebread` tinyint(1) DEFAULT NULL,
`specialrequest` text,
`customizations` text,
`price` decimal(9,2) NOT NULL,
`fav_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `order_id` (`order_id`)
) ENGINE=MyISAM AUTO_INCREMENT=9647592 DEFAULT CHARSET=latin1;
INSERT INTO `order_items` (`id`, `order_id`, `menuitem_id`, `quantity`, `whofor`, `choppingpreference`, `in_a_wrap`, `dressingpreference`, `includebread`, `specialrequest`, `customizations`, `price`, `fav_id`)
VALUES
(9647591, 5443021, 451, 1, '', '', NULL, '', 0, '', '[]', 1.99, 0),
(9647581, 5443021, 43, 1, 'Alex', 'yes', NULL, 'yes', 0, 'This is a special request', '{\"45\":1,\"80\":1,\"93\":1}', 14.86, 0);
INSERT INTO `orders` (`id`, `user_id`, `deliveryaddress_id`, `billingaddress_id`, `delivery_type`, `store_id`, `placed_by`, `ordercreated_ts`, `orderplaced_ts`, `orderread_ts`, `orderfulfilled_ts`, `order_status`)
VALUES
(5443021, 12345, 0, 0, 'D', 6, 0, '2017-08-17 16:35:15', '2017-08-17 16:36:13', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '');
INSERT INTO `order_payments` (`id`, `user_id`, `order_id`, `subtotal`, `tax`, `secondary_tax`, `soda_tax`, `delivery_fee`, `tip`, `discount`, `total`, `payment_method`, `payment_details`, `payment_collected`)
VALUES
(5277851, 0, 5443021, 16.85, 1.50, 0.00, 0.00, 1.99, 3.03, 0.00, 20.34, 'Credit Card', '1647057284', '1');
and sqlfiddle of same: http://www.sqlfiddle.com/#!9/89024b/7
Try to replace the aggregation (GROUP BY) with ORDER BY. Currently you aggregate by po.id which is unique for each order.

Selecting count from another table is only showing 1 row where it exists

I am trying to select a row count from another table even if it's empty, so if it's empty it just shows the number 0 but still selects the main table's rows.
Here's my sql:
SELECT training.*,
count(distinct training_transactions.training_transaction_course) as completed_training_payments
FROM training
INNER JOIN training_transactions
ON training.course_id = training_transactions.training_transaction_course
WHERE course_main = ?
AND course_enabled = 'enabled'
Training table:
CREATE TABLE IF NOT EXISTS `training` (
`course_id` int(11) NOT NULL,
`course_user` int(11) NOT NULL,
`course_main` int(11) NOT NULL,
`course_type` varchar(255) NOT NULL,
`course_name` varchar(255) NOT NULL,
`course_description` text NOT NULL,
`course_location` varchar(255) NOT NULL,
`course_duration` varchar(255) NOT NULL,
`course_fitness_type` varchar(255) NOT NULL,
`course_instructor_name` varchar(255) NOT NULL,
`course_price` int(15) NOT NULL,
`course_start_date` date NOT NULL,
`course_max_attendees` int(8) NOT NULL,
`course_accommodation` varchar(255) NOT NULL,
`course_accommodation_price` varchar(255) NOT NULL,
`course_status` varchar(50) NOT NULL,
`course_enabled` varchar(10) NOT NULL DEFAULT 'enabled',
`course_location_name` varchar(255) NOT NULL,
`course_location_street` varchar(255) NOT NULL,
`course_location_town` varchar(255) NOT NULL,
`course_location_county` varchar(255) NOT NULL,
`course_location_postcode` varchar(255) NOT NULL,
`course_location_country` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `training`
--
INSERT INTO `training` (`course_id`, `course_user`, `course_main`, `course_type`, `course_name`, `course_description`, `course_location`, `course_duration`, `course_fitness_type`, `course_instructor_name`, `course_price`, `course_start_date`, `course_max_attendees`, `course_accommodation`, `course_accommodation_price`, `course_status`, `course_enabled`, `course_location_name`, `course_location_street`, `course_location_town`, `course_location_county`, `course_location_postcode`, `course_location_country`) VALUES
(1, 3, 4, 'Health & Safety', 'lol', 'This is just a short description, this can be editted', '1', '13', 'lol', 'lol', 5, '1991-02-12', 4, '1', '4', 'live', 'enabled', '', '', '', '', '', 'United Kingdom'),
(2, 3, 4, 'Working at Height', 'lol', '', '1', '11', 'jkjkj', 'kjkjkj', 124, '0000-00-00', 6, '0', '', 'live', 'enabled', '', '123', '123', '123', 'WN8', 'United Kingdom'),
(3, 3, 4, 'Working at Height', 'lol', '', '1', '11', 'jkjkj', 'kjkjkj', 124, '0000-00-00', 6, '0', '', 'live', 'enabled', '', '123', '123', '123', 'WN8', 'United Kingdom');
training_transactions
CREATE TABLE IF NOT EXISTS `training_transactions` (
`training_transaction_id` int(11) NOT NULL,
`training_transaction_user` int(11) NOT NULL,
`training_transaction_course` int(11) NOT NULL,
`training_transaction_status` varchar(50) NOT NULL DEFAULT 'pending',
`training_transaction_payment_status` varchar(50) NOT NULL,
`training_transaction_cost` int(11) NOT NULL,
`training_transaction_enabled` varchar(50) NOT NULL DEFAULT 'enabled',
`training_transaction_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`training_transaction_billing_name` varchar(250) NOT NULL,
`training_transaction_billing_address1` varchar(250) NOT NULL,
`training_transaction_billing_address2` varchar(250) NOT NULL,
`training_transaction_billing_city` varchar(250) NOT NULL,
`training_transaction_billing_state` varchar(250) NOT NULL,
`training_transaction_billing_postcode` varchar(250) NOT NULL,
`training_transaction_billing_country` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `training_transactions`
--
INSERT INTO `training_transactions` (`training_transaction_id`, `training_transaction_user`, `training_transaction_course`, `training_transaction_status`, `training_transaction_payment_status`, `training_transaction_cost`, `training_transaction_enabled`, `training_transaction_date`, `training_transaction_billing_name`, `training_transaction_billing_address1`, `training_transaction_billing_address2`, `training_transaction_billing_city`, `training_transaction_billing_state`, `training_transaction_billing_postcode`, `training_transaction_billing_country`) VALUES
(1, 3, 1, 'pending', 'complete', 0, 'enabled', '2015-09-17 14:02:29', *removed my address*);
at the moment only the training course with id 1 is showing because a row in transactions exists how can I make all training display if it no id matches in the training_transactions?
Use LEFT JOIN instead of inner join to list all records from the table on the left of the join, plus you need to place the count() in a subquery to get all fields from the training table:
SELECT training.*, ifnull(T.transactioncount,0) as transactioncount
FROM training
LEFT JOIN (SELECT training_transaction_course, COUNT(training_transaction_course) as transactioncount FROM training_transactions GROUP BY training_transaction_course) AS T
ON training.course_id = T.training_transaction_course
WHERE course_main = ?
AND course_enabled = 'enabled'
INNER JOIN only selects records where records with join key in both tables exist.
With LEFT JOIN / RIGHT JOIN, selections can be made where records on one side don't exist; their field values will be NULL (and when counted, they should be zero but I'm not COMPLETELY sure of that)
Sometimes it is just easier to use sub-queries. Try this:
SELECT training.*,
(SELECT COUNT(distinct training_transactions.training_transaction_course)
FROM training_transactions
WHERE training.course_id = training_transactions.training_transaction_course) AS completed_training_payments
FROM training
WHERE training.course_main = ?
AND training.course_enabled = 'enabled'

SQL Query for amount of products sold within dates?

Fiddle Here:
http://sqlfiddle.com/#!2/2f85f4/1
I am trying to create an 'inventory demand' report essentially; what products were sold between X and Y and how much of them.
The closest I can get is this query, but this doesn't return the correct math.
Can someone please offer some guidance?
SELECT orders_products.op_products_name
, orders_products.op_products_id
, SUM(orders_products.op_products_qty) AS TotalSold
FROM orders_products
, orders
WHERE orders.orders_date_purchased
AND orders.orders_date_purchased BETWEEN '2012-11-05 00:00:00' AND '2012-11-10 00:00:00'
GROUP
BY orders_products.op_products_id
ORDER
BY TotalSold DESC
The schema is available here:
--
-- Table structure for table orders
CREATE TABLE IF NOT EXISTS orders (
orders_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
orders_date_purchased timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
orders_delivery_name varchar(100) NOT NULL,
orders_delivery_company_name varchar(100) NOT NULL,
orders_delivery_address varchar(255) NOT NULL,
orders_delivery_city varchar(100) NOT NULL,
orders_delivery_state char(2) NOT NULL,
orders_delivery_zipcode char(5) NOT NULL,
orders_delivery_phone char(10) NOT NULL,
orders_delivery_email varchar(100) NOT NULL,
orders_billing_name varchar(120) DEFAULT NULL,
orders_billing_address varchar(255) DEFAULT NULL,
orders_billing_city varchar(100) DEFAULT NULL,
orders_billing_state char(2) DEFAULT NULL,
orders_billing_zipcode char(5) DEFAULT NULL,
orders_billing_phone char(10) DEFAULT NULL,
orders_billing_email varchar(100) DEFAULT NULL,
orders_users_ID bigint(20) NOT NULL,
orders_distributor_ID bigint(20) DEFAULT NULL,
orders_affiliate_ID bigint(20) DEFAULT NULL,
orders_sales_tax decimal(11,2) NOT NULL,
orders_discount_applied decimal(11,2) DEFAULT NULL,
orders_ip_address char(15) NOT NULL,
orders_shipping_method varchar(255) NOT NULL,
orders_payment_method int(10) unsigned NOT NULL,
orders_order_total decimal(11,2) NOT NULL,
orders_shipping_cost decimal(11,2) DEFAULT NULL,
orders_total_saved decimal(11,2) NOT NULL,
orders_placed_by bigint(20) NOT NULL,
notes blob,
orders_inv_status int(11) DEFAULT NULL,
orders_date_modified timestamp NULL DEFAULT NULL,
orders_process_status int(11) DEFAULT '1',
PRIMARY KEY (orders_ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2379 ;
--
-- Dumping data for table orders
INSERT INTO orders (orders_ID, orders_date_purchased, orders_delivery_name, orders_delivery_company_name, orders_delivery_address, orders_delivery_city, orders_delivery_state, orders_delivery_zipcode, orders_delivery_phone, orders_delivery_email, orders_billing_name, orders_billing_address, orders_billing_city, orders_billing_state, orders_billing_zipcode, orders_billing_phone, orders_billing_email, orders_users_ID, orders_distributor_ID, orders_affiliate_ID, orders_sales_tax, orders_discount_applied, orders_ip_address, orders_shipping_method, orders_payment_method, orders_order_total, orders_shipping_cost, orders_total_saved, orders_placed_by, notes, orders_inv_status, orders_date_modified, orders_process_status) VALUES
(1, '2012-11-05 19:58:12', 'John Smith', '', '123 Manatee Street', 'Navarre', 'FL', '32566', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 83, NULL, NULL, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 61.59, 0.00, 0.00, 0, NULL, 8, NULL, 3),
(2, '2012-11-06 01:05:20', 'Judy Richards', '', '456 Devmor Ct', 'Navarre', 'FL', '32566', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 87, NULL, NULL, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 158.97, 0.00, 0.00, 0, NULL, 8, NULL, 3),
(4, '2012-11-08 04:32:23', 'John Smith', '', '123 Manatee Street', 'Navarre', 'FL', '32578', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 92, NULL, NULL, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 52.99, NULL, 0.00, 0, NULL, 8, '0000-00-00 00:00:00', 3),
(5, '2012-11-09 00:11:54', 'Adam Davis', '', '4307 D134 Legendary Dr.', 'Navarre', 'FL', '32541', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 89, 84, 0, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 160.51, 0.00, 0.00, 0, NULL, 8, NULL, 3),
(6, '2012-11-09 21:14:25', 'Judy Sterling', '', '2310 Lexington Lane', 'Navarre', 'FL', '32566', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 87, NULL, NULL, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 158.97, 0.00, 0.00, 0, NULL, 8, NULL, 3);
--
-- Table structure for table orders_products
CREATE TABLE IF NOT EXISTS orders_products (
orders_products_ID bigint(20) NOT NULL AUTO_INCREMENT,
op_order_id bigint(20) unsigned NOT NULL,
op_products_id bigint(20) unsigned NOT NULL,
op_products_mfr_part_number varchar(65) NOT NULL,
op_products_name varchar(15) NOT NULL,
op_products_qty bigint(10) unsigned NOT NULL,
PRIMARY KEY (orders_products_ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5923 ;
--
-- Dumping data for table orders_products
INSERT INTO orders_products (orders_products_ID, op_order_id, op_products_id, op_products_mfr_part_number, op_products_name, op_products_qty) VALUES
(1, 1, 491, 'CWP8489A001BA', 'X25', 1),
(2, 2, 2134, 'Professional Fee', 'Professional Fe', 3),
(3, 3, 473, 'CWPDR360', 'DR-360', 1),
(4, 4, 2134, 'Professional Fee', 'Professional Fe', 1),
(5, 5, 362, 'CWPDR360', 'DR-360', 1);
--
-- Table structure for table products
CREATE TABLE IF NOT EXISTS products (
products_id bigint(20) NOT NULL AUTO_INCREMENT,
products_brand varchar(200) NOT NULL,
products_brand_type varchar(200) NOT NULL,
products_mfr_part_number varchar(65) NOT NULL,
products_common_name varchar(15) NOT NULL,
products_msrp decimal(11,2) NOT NULL,
products_price decimal(11,2) NOT NULL,
products_description varchar(255) NOT NULL,
products_weight decimal(11,2) NOT NULL DEFAULT '1.00',
products_length decimal(3,2) DEFAULT NULL,
products_width decimal(3,2) DEFAULT NULL,
products_height decimal(3,2) DEFAULT NULL,
products_tax_exempt int(11) DEFAULT NULL,
PRIMARY KEY (products_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2558 ;
--
-- Dumping data for table products
INSERT INTO products (products_id, products_brand, products_brand_type, products_mfr_part_number, products_common_name, products_msrp, products_price, products_description, products_weight, products_length, products_width, products_height, products_tax_exempt) VALUES
(1, 'HP', 'Original', '92298A ', '98A', 132.99, 131.66, 'Genuine HP® LaserJet 98A Black Toner Cartridge (92298A) ', 4.20, 9.99, 6.14, 9.72, NULL),
(2, 'HP', 'Original', 'C3903A ', '03A', 112.99, 111.86, 'Genuine HP® LaserJet 03A Black Toner Cartridge (C3903A) ', 3.00, 9.99, 4.80, 7.72, NULL),
(3, 'HP', 'Original', 'C3906A ', '06A', 87.99, 87.11, 'Genuine HP® LaserJet 06A Black Toner Cartridge (C3906A)', 2.13, 9.99, 5.16, 6.50, NULL),
(4, 'HP', 'Original', 'C3909A', '09A', 254.99, 252.44, 'Genuine HP® LaserJet 09A Black Toner Cartridge (C3909A)', 3.31, 9.99, 4.72, 8.07, NULL),
(5, 'HP', 'Original', 'C4092A ', '92A', 75.99, 75.23, 'Genuine HP® LaserJet 92A Black Toner Cartridge (C4092A) ', 2.20, 9.99, 5.16, 6.50, NULL);
The major problem is that you need a join condition between orders_products and orders. You have a , which is equivalent to cross join. As a simple rule: never use commas in the from clause.
In addition, the where clause was awkwardly phrased. Here is a rewrite of your query that also uses table aliases for readability:
SELECT op.op_products_name, op.op_products_id, SUM(op.op_products_qty) AS TotalSold
FROM orders_products op JOIN
orders o
ON op.op_order_id = o.orders_id
WHERE o.orders_date_purchased BETWEEN '2012-11-05 00:00:00' AND '2012-11-10 00:00:00'
GROUP BY op.op_products_id
ORDER BY TotalSold DESC;