Select subscriptions based on user id - mysql

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;

Related

MySQL - Why query does not sum same type of data if I use more left join?

My schema and sample data set:
CREATE TABLE `bsbi_hedge_fund` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`fund_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`abn_number` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
`parent_company_id` int(11) DEFAULT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`contact_no` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
`address_one` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`address_two` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`city_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`state_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`zip_code` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`country_tbl_id` int(11) DEFAULT NULL,
`status` varchar(10) COLLATE utf8_unicode_ci DEFAULT 'active',
`created_by` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
`modified_by` int(11) DEFAULT NULL,
`modified_date` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bsbi_hedge_fund`
--
INSERT INTO `bsbi_hedge_fund` (`id`, `fund_name`, `abn_number`, `parent_company_id`, `email`, `contact_no`, `address_one`, `address_two`, `city_name`, `state_name`, `zip_code`, `country_tbl_id`, `status`, `created_by`, `created_date`, `modified_by`, `modified_date`) VALUES
(1, 'iCAP Hedge Funds', '53616271062', 1, 'icaptrading#gmail.com', '0425175887', '68 Roy Marika Street', '', 'Bonner', 'ACT', '2914', 12, 'active', 1, '2020-02-20 07:02:51', NULL, NULL);
CREATE TABLE `bsbi_company` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`company_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`abn_number` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
`acn_number` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`contact_no` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
`address_one` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`address_two` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`city_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`state_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`zip_code` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`country_tbl_id` int(11) DEFAULT NULL,
`status` varchar(10) COLLATE utf8_unicode_ci DEFAULT 'active',
`created_by` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
`modified_by` int(11) DEFAULT NULL,
`modified_date` datetime DEFAULT NULL,
`allocated_money` float(17,5) DEFAULT '0.00000',
`hedge_fund_allocation` float(17,5) NOT NULL,
`investment_class_allocation` float(17,5) NOT NULL,
`hedge_fund_money` float(10,3) DEFAULT '0.000',
`inv_class_money` float(10,3) DEFAULT '0.000'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bsbi_company`
--
INSERT INTO `bsbi_company` (`id`, `company_name`, `abn_number`, `acn_number`, `email`, `contact_no`, `address_one`, `address_two`, `city_name`, `state_name`, `zip_code`, `country_tbl_id`, `status`, `created_by`, `created_date`, `modified_by`, `modified_date`, `allocated_money`, `hedge_fund_allocation`, `investment_class_allocation`, `hedge_fund_money`, `inv_class_money`) VALUES
(1, 'Investment and Capital Growth for Australian Professional ( ', '53616271062', '2123', 'abc#gmail.com', '2343', '68 Roy Marika Street', '', 'Bonner', 'ACT', '2914', 12, 'active', 1, '2020-02-20 07:01:26', 1, '2020-03-07 12:13:53', 22847.00000, 0.00000, 0.00000, 20000.000, 19000.000);
CREATE TABLE `bsbi_hedge_fund_journal` (
`id` int(11) NOT NULL,
`company_id` int(11) DEFAULT NULL,
`hedge_fund_id` int(11) DEFAULT NULL,
`amount` float(10,3) DEFAULT NULL,
`tran_type` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_by` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
`modified_by` int(11) DEFAULT NULL,
`modified_date` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bsbi_hedge_fund_journal`
--
INSERT INTO `bsbi_hedge_fund_journal` (`id`, `company_id`, `hedge_fund_id`, `amount`, `tran_type`, `created_by`, `created_date`, `modified_by`, `modified_date`) VALUES
(1, 1, 1, 20000.000, 'credit', 1, '2020-03-07 11:45:40', NULL, NULL);
CREATE TABLE `bsbi_investment_allocation_class_journal` (
`id` int(11) NOT NULL,
`hedge_fund_id` int(11) DEFAULT NULL,
`investment_class_id` int(11) DEFAULT NULL,
`amount` float(10,3) DEFAULT NULL,
`tran_type` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_by` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bsbi_investment_allocation_class_journal`
--
INSERT INTO `bsbi_investment_allocation_class_journal` (`id`, `hedge_fund_id`, `investment_class_id`, `amount`, `tran_type`, `created_by`, `created_date`) VALUES
(1, 1, 1, 18000.000, 'credit', 1, '2020-03-07 11:46:09'),
(2, 1, 1, 2000.000, 'credit', 1, '2020-03-07 12:12:02'),
(3, 1, 1, 1000.000, 'debit', 1, '2020-03-07 12:13:53');
...and fiddle of same ( http://sqlfiddle.com/#!9/9cd46d/2 ):
I have written the following query to fetch some data from the database:
SELECT
hf.*, com.company_name company_name, com.id com_id,
IFNULL( SUM( hfc.amount ), 0 ) hedge_credit, IFNULL( SUM( hfd.amount ), 0 ) hedge_debit,
IFNULL( SUM( cjc.amount ), 0 ) class_credit, IFNULL( SUM( cjd.amount ), 0 ) class_debit
FROM bsbi_hedge_fund hf
INNER JOIN bsbi_company com ON hf.parent_company_id = com.id
LEFT JOIN bsbi_hedge_fund_journal hfc ON (hfc.hedge_fund_id = hf.id AND hfc.tran_type='credit')
LEFT JOIN bsbi_hedge_fund_journal hfd ON ( hfd.hedge_fund_id = hf.id AND hfd.tran_type = 'debit' )
LEFT JOIN bsbi_investment_allocation_class_journal cjc ON (cjc.hedge_fund_id = hf.id AND cjc.tran_type = 'credit' )
LEFT JOIN bsbi_investment_allocation_class_journal cjd ON (cjd.hedge_fund_id = hf.id AND cjd.tran_type = 'debit' )
ORDER BY hf.id ASC
Here is the output of this query:
The problem I face is: hedge_credit value is 20000 but it shows 40000! similarly class_debit is 1000 but it shows 2000
After doing some R&D what I found is: bsbi_investment_allocation_class_journal table has two entry having tran_type = credit but for some unknown reason the following line of my query fetch two rows, rather sum the values (and I fear the same thing will happen to other left join if they also have more than one record of the same type!)
LEFT JOIN bsbi_investment_allocation_class_journal cjc ON (cjc.hedge_fund_id = hf.id AND cjc.tran_type = 'credit' )
If I add Group By clause to above query then I got:
Notice that class_credit has two different values that should sum up but does not sum for an unknown reason!!
Can anyone tell me what is actually wrong in my query that raises this issue?
- Thanks
Joins generate all possible combinations of rows that meet join criteria. Because you're using only hfc.hedge_fund_id = hf.id to join tables, you are duplicating rows. If there were three transactions in total, each would be tripled..
You'll need to select more data from the tables containing transactions to keep the rows unique: timestamps or transaction ids. I would usually select the unique rows that I want first, then left join the non-unique data (name, country, etc) to each row.
I got the solution from this: https://dba.stackexchange.com/questions/154586/sum-over-distinct-rows-with-multiple-joins
If someone faces the exact type of problem then they can check this solution: https://dba.stackexchange.com/questions/154586/sum-over-distinct-rows-with-multiple-joins

Mysql join multiple tables with one select phrase

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;

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.

Data too long for column 'Subscribe_Specialty' at row 1 - Mysql error

Here is the insert statement -
INSERT INTO `Newsletter_Subscriber_Uploaded_Data`(`File_Id`, `First_Name`, `Last_Name`, `Email`,`Country`,`Country_Id`,`Subscribe_Specialty`,Is_Valid, `Subscription_Id`, `User_Id`, `Created_Date`)
VALUES (2, 'Adolphus','Bonar', 'a.bonar#endocrinology.org', 'United States','2', 'General Practice/Family Medicine', 1 ,20, '89',CURRENT_TIMESTAMP)
For column Subscribe_Specialty, the value I'm trying to insert is 'General Practice/Family Medicine' which has only 32 characters, but still it is giving me the above error.
Please help me guys, as this is a production error.
More Information:
Collation : utf8
Storage Engine : InnoDB
Below is the Table structure -
CREATE TABLE `Newsletter_Subscriber_Uploaded_Data` (
`File_Id` int(11) NOT NULL,
`Row_Id` int(11) NOT NULL AUTO_INCREMENT,
`First_Name` varchar(50) NOT NULL,
`Last_Name` varchar(50) NOT NULL,
`Email` varchar(100) DEFAULT NULL,
`Country` varchar(20) NOT NULL,
`Country_Id` int(11) NOT NULL DEFAULT '0',
`Subscribe_Specialty` varchar(100) NOT NULL,
`Is_Valid` tinyint(4) DEFAULT '0',
`Subscription_Id` int(100) NOT NULL DEFAULT '0',
`Duplicate` tinyint(4) DEFAULT '0',
`Subscriber` tinyint(4) DEFAULT '0',
`Created_Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`User_Id` int(11) NOT NULL COMMENT 'Panel user id',
PRIMARY KEY (`Row_Id`),
KEY `File_Id` (`File_Id`)
) ENGINE=InnoDB AUTO_INCREMENT=21511 DEFAULT CHARSET=utf8;

Out of memory error - Error Code: 2008 MySQL client ran out of memory

I was trying to run the below query inside either mySQL workbench or dbForge, or even asp.net website, however I am always getting "out of memory exception".
The database is huge, and there are a lot of records need to be returned. I have read through some of the other questions that I need to slicing down the query to use less memory, but this is a UNION JOIN with 2 simple select statements, from 3 different tables. How can I possible to reduce this?
SELECT
t.TICKET as 'Ticket',
t.LOGIN as 'Login Id',
u.Name,
t.OPEN_Time as 'Open Time',
(CASE WHEN t.CLOSE_Time>#CONST_EMPTY_DATE THEN t.CLOSE_time ELSE NULL END) as 'Close Time/Liquidation Time',
(CASE WHEN t.CMD=#CMD_OP_BUY then 'Buy' ELSE 'Sell' END) as 'Type/Liquidation Action',
t.SYMBOL as 'Symbol',
t.VOLUME/100.0 as 'Volume',
t.OPEN_PRICE as 'Open Price',
t.SL as 'S/L',
t.TP as 'T/P',
t.CLOSE_PRICE as 'Closed Price',
t.SWAPS as 'Swap',
(t.VOLUME/100.0)*lots.`Lot Size`*t.OPEN_PRICE as 'Open amount of money',
(t.VOLUME/100.0)*lots.`Lot Size`* t.CLOSE_PRICE as 'Closed amount of money',
t.PROFIT as 'Profit',
t.COMMISSION as 'Commission',
(CASE
WHEN u.GROUP like '%USD%' THEN 'USD'
WHEN u.GROUP like '%EUR%' THEN 'EUR'
WHEN u.GROUP like '%JPY%' THEN 'JPY'
WHEN u.GROUP like '%GBP%' THEN 'GBP'
ELSE '???' END) as 'Currency',
t.SERVER_ID as 'server ID'
FROM
trades t
INNER JOIN users u ON t.LOGIN=u.LOGIN
AND t.SERVER_ID = u.SERVER_ID
and t.CMD IN (#CMD_OP_BUY,#CMD_OP_SELL)
#and t.CLOSE_TIME between fromdate and todate
#and u.LOGIN = inlogin
and t.HISTORY = 'N'
inner join lotsize lots on t.SYMBOL = lots.Name
where t.close_time > '2012-09--17 00:00:00' and t.close_time < '2012-09-24 00:00:00'
UNION ALL
Select
Null as 'Ticket',
l.LOGIN as 'Login Id',
u.Name,
Null as 'Open Time',
l.liquidation_timestamp as 'Close Time/Liquidation Time',
l.liquidation_action as 'Type/Liquidation Action',
Null as 'Symbol',
Null as 'Volume',
Null as 'Open Price',
Null as 'S/L',
Null as 'T/P',
Null as 'Closed Price',
Null as 'Swap',
Null as 'Open amount of money',
Null as 'Closed amount of money',
Null as 'Profit',
Null as 'Commission',
(CASE
WHEN u.GROUP like '%USD%' THEN 'USD'
WHEN u.GROUP like '%EUR%' THEN 'EUR'
WHEN u.GROUP like '%JPY%' THEN 'JPY'
WHEN u.GROUP like '%GBP%' THEN 'GBP'
ELSE '???' END) as 'Currency',
l.SERVER_ID as 'MT4 server ID'
From liquidations as l
INNER JOIN users as u ON l.LOGIN=u.LOGIN
AND l.SERVER_ID = u.SERVER_ID;
I think I need to mention that if I run either of the select query seperatly, then it will give me the correct results. It is just when using the UNION to join them together, I am getting the out of memory error.
Trade table
'mt4_trades', 'CREATE TABLE `mt4_trades` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`TICKET` int(11) DEFAULT NULL,
`LOGIN` int(11) DEFAULT NULL,
`SYMBOL` char(16) DEFAULT NULL,
`DIGITS` int(11) DEFAULT NULL,
`CMD` int(11) DEFAULT NULL,
`VOLUME` int(11) DEFAULT NULL,
`OPEN_TIME` datetime DEFAULT NULL,
`OPEN_PRICE` double DEFAULT NULL,
`SL` double DEFAULT NULL,
`TP` double DEFAULT NULL,
`CLOSE_TIME` datetime DEFAULT NULL,
`EXPIRATION` datetime DEFAULT NULL,
`CONV_RATE1` double DEFAULT NULL,
`CONV_RATE2` double DEFAULT NULL,
`CONV_RATE3` double DEFAULT NULL,
`COMMISSION` decimal(18,2) DEFAULT NULL,
`COMMISSION_AGENT` decimal(18,2) DEFAULT NULL,
`SWAPS` decimal(18,2) DEFAULT NULL,
`CLOSE_PRICE` double DEFAULT NULL,
`PROFIT` decimal(18,2) DEFAULT NULL,
`TAXES` decimal(18,2) DEFAULT NULL,
`COMMENT` char(128) DEFAULT NULL,
`INTERNAL_ID` int(11) DEFAULT NULL,
`MARGIN_RATE` double DEFAULT NULL,
`TIMESTAMP` int(11) DEFAULT NULL,
`MODIFY_TIME` datetime DEFAULT NULL,
`MODIFY_REASON` varchar(256) DEFAULT NULL,
`HISTORY` char(1) DEFAULT NULL,
`BALANCE` decimal(18,2) DEFAULT NULL,
`MT4_SERVER_ID` varchar(30) DEFAULT '''',
PRIMARY KEY (`ID`),
KEY `mt4_trades_ticket_history_server_id_i` (`TICKET`,`HISTORY`,`MT4_SERVER_ID`),
KEY `mt4_trades_login_server_id_history_i` (`LOGIN`,`MT4_SERVER_ID`,`HISTORY`),
KEY `mt4_cmd_i` (`CMD`),
KEY `mt4_open_time_i` (`OPEN_TIME`),
KEY `mt4_close_time_i` (`CLOSE_TIME`)
) ENGINE=InnoDB AUTO_INCREMENT=16427471 DEFAULT CHARSET=utf8'
User table
'mt4_users', 'CREATE TABLE `mt4_users` (
`MODIFY_TIME` datetime DEFAULT NULL,
`LOGIN` int(11) NOT NULL DEFAULT ''0'',
`USER_GROUP` varchar(30) DEFAULT NULL,
`BALANCE` decimal(18,2) DEFAULT NULL,
`PREVMONTHBALANCE` decimal(18,2) DEFAULT NULL,
`PREVBALANCE` decimal(18,2) DEFAULT NULL,
`PREVMONTHEQUITY` decimal(18,2) DEFAULT NULL,
`PREVEQUITY` decimal(18,2) DEFAULT NULL,
`BALANCE_STATUS` int(11) DEFAULT NULL,
`EQUITY` decimal(18,2) DEFAULT NULL,
`MARGIN` decimal(18,2) DEFAULT NULL,
`MARGIN_LEVEL` decimal(18,2) DEFAULT NULL,
`MARGIN_FREE` decimal(18,2) DEFAULT NULL,
`CREDIT` decimal(18,2) DEFAULT NULL,
`MODIFY_REASON` varchar(128) DEFAULT NULL,
`NAME` varchar(128) DEFAULT NULL,
`EMAIL` varchar(48) DEFAULT NULL,
`COMMENT` varchar(64) DEFAULT NULL,
`MT4_SERVER_ID` varchar(30) NOT NULL DEFAULT '''',
`GROUP` varchar(30) DEFAULT NULL,
`ADDRESS` varchar(128) DEFAULT NULL,
PRIMARY KEY (`LOGIN`,`MT4_SERVER_ID`),
UNIQUE KEY `mt4_users_uk` (`GROUP`,`LOGIN`,`MT4_SERVER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8'
Liquidation table
'mt4_liquidations', 'CREATE TABLE `mt4_liquidations` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`LOGIN` int(11) DEFAULT NULL,
`LIQUIDATION_ACTION` char(1) DEFAULT NULL,
`LIQUIDATION_TIMESTAMP` datetime DEFAULT NULL,
`EQUITY_BEFORE_LIQUIDATION` decimal(18,2) DEFAULT NULL,
`MARGIN_BEFORE_LIQUIDATION` decimal(18,2) DEFAULT NULL,
`BALANCE_BEFORE_LIQUIDATION` decimal(18,2) DEFAULT NULL,
`MT4_SERVER_ID` varchar(30) NOT NULL DEFAULT '''',
PRIMARY KEY (`ID`,`MT4_SERVER_ID`),
KEY `Login` (`LOGIN`),
KEY `liquidation_timestamp` (`LOGIN`,`LIQUIDATION_TIMESTAMP`)
) ENGINE=InnoDB AUTO_INCREMENT=10526248 DEFAULT CHARSET=utf8'
Output of the explain query
'1', 'PRIMARY', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'Impossible WHERE noticed after reading const tables'
'2', 'UNION', 'l', 'ALL', 'Login,liquidation_timestamp', NULL, NULL, NULL, '10502418', ''
'2', 'UNION', 'u', 'eq_ref', 'PRIMARY', 'PRIMARY', '96', 'l.LOGIN,l.MT4_SERVER_ID', '1', ''
NULL, 'UNION RESULT', '<union1,2>', 'ALL', NULL, NULL, NULL, NULL, NULL, ''