multiple sum in my sql - mysql

Trying to get result in single query however unable to get correct sum of order stock, it display sum twice if waste item exits.
Please see below query
SELECT DISTINCT cd.id,i.*,c.category_name, SUM(CASE WHEN s.stock_type = 'f' THEN s.stock END) AS instock, SUM(CASE WHEN s.stock_type = 'w' THEN s.stock END) AS weststock, SUM(cd.qty) AS orderstock, IF(SUM(CASE WHEN s.stock_type = 'f' THEN s.stock END) IS NULL,0, SUM(CASE WHEN s.stock_type = 'f' THEN s.stock END)) - IF(SUM(CASE WHEN s.stock_type = 'w' THEN s.stock END) IS NULL,0, SUM(CASE WHEN s.stock_type = 'w' THEN s.stock END)) - IF(SUM(cd.qty) IS NULL,0, SUM(cd.qty)) AS total
FROM item AS i
JOIN categories AS c ON i.category_id = c.id
LEFT JOIN stock AS s ON i.id=s.item_id
LEFT JOIN manage_godown AS mg ON mg.id = s.godown_id
LEFT JOIN cart_detail AS cd ON i.id=cd.item_id AND cd.cart_id IN (
SELECT ca.id
FROM cart AS ca
WHERE ca.status ='o')
WHERE mg.id=8
GROUP BY i.id
ORDER BY i.id DESC
Table Structure
----------------------
--
-- Table structure for table `admin`
--
CREATE TABLE IF NOT EXISTS `admin` (
`id` double NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`mobile_no` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`status` enum('a','d') NOT NULL COMMENT 'a= active,d=deactive',
`type` enum('a','m') NOT NULL DEFAULT 'm',
`last_login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`change_password_key` text NOT NULL,
`isAsigned` enum('y','n') NOT NULL DEFAULT 'n',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
-- --------------------------------------------------------
--
-- Table structure for table `area`
--
CREATE TABLE IF NOT EXISTS `area` (
`id` double NOT NULL AUTO_INCREMENT,
`area_name` varchar(255) NOT NULL,
`area_status` enum('a','d') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
-- --------------------------------------------------------
--
-- Table structure for table `cart`
--
CREATE TABLE IF NOT EXISTS `cart` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` double NOT NULL,
`date` datetime NOT NULL,
`status` enum('c','o') NOT NULL DEFAULT 'c',
`ship_status` enum('y','n') NOT NULL DEFAULT 'n',
`shiping_address` text NOT NULL,
`order_date` datetime NOT NULL,
`area_id` int(11) NOT NULL,
`user_name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`contact_number` varchar(255) NOT NULL,
`address` text NOT NULL,
`shipping_name` varchar(255) NOT NULL,
`order_delivery_status` enum('p','d','c') NOT NULL COMMENT 'p=pending,d=deliverd,c=cancle',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
-- --------------------------------------------------------
--
-- Table structure for table `cart_detail`
--
CREATE TABLE IF NOT EXISTS `cart_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cart_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`qty` double NOT NULL,
`amount` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE IF NOT EXISTS `categories` (
`id` double NOT NULL AUTO_INCREMENT,
`category_name` varchar(255) NOT NULL,
`isDefault` enum('y','n') NOT NULL DEFAULT 'n',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
-- --------------------------------------------------------
--
-- Table structure for table `item`
--
CREATE TABLE IF NOT EXISTS `item` (
`id` double NOT NULL AUTO_INCREMENT,
`category_id` double NOT NULL,
`item_name` varchar(255) NOT NULL,
`item_image` text NOT NULL,
`price` double NOT NULL,
`isPopular` enum('Y','N') NOT NULL,
`item_status` enum('a','d') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;
-- --------------------------------------------------------
--
-- Table structure for table `manage_godown`
--
CREATE TABLE IF NOT EXISTS `manage_godown` (
`id` double NOT NULL AUTO_INCREMENT,
`godown_name` varchar(150) NOT NULL,
`address` text NOT NULL,
`contact_number` varchar(50) NOT NULL,
`contact_person` varchar(255) NOT NULL,
`area_id` text NOT NULL,
`user_id` varchar(100) NOT NULL,
`godown_status` enum('a','d') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `area`
--
INSERT INTO `area` (`id`, `area_name`, `area_status`) VALUES
(1, 'C.G. Road', 'a'),
(2, 'S.G. Highway', 'a'),
(3, 'Bopal', 'a'),
(4, 'New Wadaj', 'a'),
(5, 'Ranip', 'a'),
(6, 'Bapunagar', 'a'),
(7, 'Gurukul RD', 'a'),
(8, 'Ghatlodia', 'a'),
(9, 'Nehru Nagar', 'a'),
(10, 'Old Wadaj', 'a'),
(11, 'Paldi', 'a'),
(12, 'NaranPura', 'a'),
(13, 'Anand Nagar', 'd'),
(14, 'Shahpur', 'a');
--
-- Dumping data for table `cart`
--
INSERT INTO `cart` (`id`, `user_id`, `date`, `status`, `ship_status`, `shiping_address`, `order_date`, `area_id`, `user_name`, `email`, `contact_number`, `address`, `shipping_name`, `order_delivery_status`) VALUES
(1, 1, '2015-03-09 20:30:36', 'o', 'n', 'roam', '2015-03-09 21:14:45', 7, 'account1', 'account1#superrito.com', '123456', 'roam', 'account1', 'p'),
(2, 1425936687, '2015-03-09 21:31:27', 'c', 'n', '', '0000-00-00 00:00:00', 0, '', '', '', '', '', 'p'),
(3, 1426012764, '2015-03-10 18:39:24', 'c', 'n', '', '0000-00-00 00:00:00', 0, '', '', '', '', '', 'p');
--
-- Dumping data for table `cart_detail`
--
INSERT INTO `cart_detail` (`id`, `cart_id`, `item_id`, `qty`, `amount`) VALUES
(1, 1, 1, 3, 80),
(2, 2, 1, 0.25, 80),
(3, 3, 1, 0.5, 80),
(4, 3, 2, 0.25, 45);
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `category_name`, `isDefault`) VALUES
(1, 'vegitables', 'y'),
(2, 'fruits', 'y');
--
-- Dumping data for table `item`
--
INSERT INTO `item` (`id`, `category_id`, `item_name`, `item_image`, `price`, `isPopular`, `item_status`) VALUES
(1, 1, 'Tomato', '210fc803a958749e7b2a55c32c744f13.png', 80, 'Y', 'a'),
(2, 1, 'Potato', 'c244be2eab10bc46465d5b36448ba68b.jpg', 45, 'N', 'a'),
(3, 2, 'Cabbige', '05423c579cc99709923273c5222c4661.jpg', 120, 'Y', 'a');
--
-- Dumping data for table `manage_godown`
--
INSERT INTO `manage_godown` (`id`, `godown_name`, `address`, `contact_number`, `contact_person`, `area_id`, `user_id`, `godown_status`) VALUES
(8, 'Gurukul', 'Gurukul RD', '12457894', 'Salim', '7', '16', 'a'),
(9, 'Godown2', 'Godown2', '123456798', 'Samln', '12', '17', 'a');
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id`, `email`, `user_name`, `address`, `shiping_address`, `mobile_no`, `password`, `isVeryfied`, `created_date`, `email_verification`, `change_password_key`, `area_id`, `pincode`, `user_status`) VALUES
(1, 'account1#superrito.com', 'account1', 'roam', 'roam', '123456', '4b111bc4e9e96cd1d18d0359fdb94629', 'n', '2015-03-09 08:53:00', '', '', 0, 0, 'a'),
(2, 'tripathi_hhh#yahoo.com', 'hitesh tripathi', '', '', '9033913397', 'e10adc3949ba59abbe56e057f20f883e', 'n', '2015-03-10 06:31:23', '17a962a2eee74445747a3e194da6c556', 'be45b6a9362c65217ec88821b648a67f', 0, 0, 'a');
I placed order of Tomato 3KG Only however i added wasted item 3 times so sum of above query gives result 12KG in orderstock

Using COALESCE instead of IF ... IS NULL makes it a lot more readable... I'm waiting on your answer to #EdwinKrause's question to help with the rest.
SELECT DISTINCT cd.id,i.*,c.category_name,
SUM(CASE WHEN s.stock_type = 'f' THEN s.stock END) AS instock,
SUM(CASE WHEN s.stock_type = 'w' THEN s.stock END) AS weststock,
SUM(cd.qty) AS orderstock,
COALESCE( SUM(CASE WHEN s.stock_type = 'f' THEN s.stock END), 0) -
COALESCE(SUM(CASE WHEN s.stock_type = 'w' THEN s.stock END), 0) -
COALESCE(SUM(cd.qty), 0) AS total
FROM item AS i
JOIN categories AS c ON i.category_id = c.id
LEFT JOIN stock AS s ON i.id=s.item_id
LEFT JOIN manage_godown AS mg ON mg.id = s.godown_id
LEFT JOIN cart_detail AS cd ON i.id=cd.item_id AND cd.cart_id IN (
SELECT ca.id
FROM cart AS ca
WHERE ca.status ='o')
WHERE mg.id=2
GROUP BY i.id
ORDER BY i.id DESC

Related

MySQL get all parents

We have orders and RMA's. RMA's can be created with order_products of an order. If in the RMA a new product is send, the product can also be added to a new RMA, and so on.
Now for example, I have this schematic structure of an order with RMA orders.
Order (1)
|-> RMA (2)
|-> RMA (3)
|-> RMA (4)
|-> RMA (5)
Now I want to traverse up from RMA (5), all the way up. So actually I want to get 5 records from the database containing all the RMA's and the original order (All from the order table). How can I do this, given the database structure shown below.
Here is a SQLFiddle.
CREATE TABLE `order` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`type` varchar(5) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
CREATE TABLE `order_product` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`order_id` int(11) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `order_rma_product` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`order_id` int(11) DEFAULT NULL,
`order_product_id` int(11) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
INSERT INTO `order` (`id`, `type`, `description`)
VALUES
(1, 'order', 'Original order'),
(2, 'rma', 'RMA of order 1'),
(3, 'rma', 'RMA of order 2'),
(4, 'rma', 'RMA of order 3'),
(5, 'rma', 'RMA of order 4');
INSERT INTO `order_product` (`id`, `order_id`, `description`)
VALUES
(1, 1, 'Product'),
(2, 2, 'Product'),
(3, 3, 'Product'),
(4, 4, 'Product');
INSERT INTO `order_rma_product` (`id`, `order_id`, `order_product_id`, `description`)
VALUES
(1, 2, 1, 'Return product'),
(2, 3, 2, 'Return product'),
(3, 4, 3, 'Return product'),
(4, 5, 4, 'Return product');
I have tried this, but this give's me one row, so i tried contact_ws to get them all in on column. But this only works for the given set of JOINS, so not unlimited going up.
SELECT CONCAT_WS(',', op.order_id, op1.order_id, op2.order_id)
FROM `order` o
JOIN order_rma_product orp ON o.id = orp.order_id
JOIN order_product op ON orp.order_product_id = op.id
JOIN order_rma_product orp1 ON op.order_id = orp1.order_id
JOIN order_product op1 ON orp1.order_product_id = op1.id
JOIN order_rma_product orp2 ON op1.order_id = orp2.order_id
JOIN order_product op2 ON orp2.order_product_id = op2.id
WHERE o.id = '5';

Else is not running in mysql Query

I have below query. In this I have yes and no case.
yes is accessing but else part is not working . Please have a look on this.
SELECT SalesChannel.name , count(Transaction.category_id) as count, (case when (Transaction.no_of_units > 0 and Transaction.mop > 0) THEN 'yes' ELSE 'No' END) AS Is_Present from outlets Outlet inner join transactions Transaction on Outlet.id = Transaction.outlet_id inner join sale_channels SalesChannel on SalesChannel.id = Outlet.sale_channel_id group by SalesChannel.name
the output should be as below
KU Electrical
Yes 6 2
No 1 2
6 is counter of KU and Yes refers the presence,similarly No is non presence of KU
select SalesChannel.name ,
Transaction.category_id,
count(Transaction.category_id) as count,
from outlets Outlet inner join transactions Transaction on Outlet.id = Transaction.outlet_id inner join sale_channels SalesChannel on SalesChannel.id = Outlet.sale_channel_id group by SalesChannel.name
below are three tables which i used
1. transactions
CREATE TABLE IF NOT EXISTS `transactions` (
`id` int(11) NOT NULL,
`zone_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`sub_category_id` int(11) NOT NULL,
`brand_id` int(11) NOT NULL,
`model_id` int(11) NOT NULL,
`outlet_id` int(11) NOT NULL,
`no_of_units` int(11) NOT NULL,
`mop` decimal(10,2) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `transactions`
--
INSERT INTO `transactions` (`id`, `zone_id`, `state_id`, `city_id`, `category_id`, `sub_category_id`, `brand_id`, `model_id`, `outlet_id`, `no_of_units`, `mop`) VALUES
(1, 2, 2, 2, 2, 1, 1, 1, 1, 3, '6.00'),
(2, 2, 2, 2, 2, 1, 1, 1, 1, 3, '6.00'),
(3, 1, 1, 1, 1, 1, 1, 1, 1, 4, '2.00'),
(4, 2, 2, 2, 1, 1, 1, 1, 2, 4, '2.00');
2.outlets
CREATE TABLE IF NOT EXISTS `outlets` (
`id` int(11) NOT NULL,
`outlet_code` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`zone_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
`sale_channel_id` int(11) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `outlets`
--
INSERT INTO `outlets` (`id`, `outlet_code`, `name`, `zone_id`, `state_id`, `city_id`, `sale_channel_id`, `is_active`, `created`, `modified`) VALUES
(1, '1508', 'Ashok electricals', 2, 2, 2, 1, 1, '2016-10-03 00:00:00', '2016-10-03 00:00:00'),
(2, '1233', 'vinayak electricals', 1, 1, 1, 2, 1, '2016-10-04 00:00:00', '2016-10-04 00:00:00');
3. sale_chennals
CREATE TABLE IF NOT EXISTS `sale_channels` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `sale_channels`
--
INSERT INTO `sale_channels` (`id`, `name`, `is_active`, `created`, `modified`) VALUES
(1, 'KU', 1, '2016-10-03 00:00:00', '2016-10-03 00:00:00'),
(2, 'Electricals', 1, '2016-10-04 00:00:00', '2016-10-04 00:00:00');
There is no data in tables that match for the else condition. Your condition is that "Transaction.no_of_units >0 AND Transaction.mop >0" that is not match in table value of both fields are greater than 0.
Otherwise, else condition works fine.
You are aggregating your data so as to get one row per SalesChannel.name. There may be some transaction records that result in 'Yes' and others in 'No' for a SalesChannel.name, so what then is Is_Present supposed to be?
Another issue with your query is that the sale channels are in a table. There are currently two of them, but there could be three or four or thousands sometime. A SQL query doesn't produce a result with a variable number of columns. The columns must be known beforehand. So a possible result could look like this:
Name Yes No
KU 6 1
Electrical 2 2
because you know you want it to be Yes or No only, no matter how many channels.
The query:
select
sc.name,
count(case when t.no_of_units > 0 and t.mop > 0 then 1 end) as yes,
count(case when t.no_of_units <= 0 or t.mop <= 0 then 1 end) as no
from sale_channels sc
join outlet o on o.sale_channel_id = sc.id
join transactions t on t.outlet_id = o.id;

SQL issues in JOIN statement

I have these 4 tables:
CREATE TABLE IF NOT EXISTS `football_league` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`league` int(11) NOT NULL,
`country` int(11) NOT NULL,
`code` int(11) NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
CREATE TABLE IF NOT EXISTS `football_goals` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`match` int(11) NOT NULL,
`team` int(11) NOT NULL,
`goals` int(11) NOT NULL,
`time` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `match` (`match`),
KEY `team` (`team`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
CREATE TABLE IF NOT EXISTS `football_matches` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pcode` varchar(32) NOT NULL,
`date` date NOT NULL,
`time` time NOT NULL,
`team_1` int(11) NOT NULL,
`team_2` int(11) NOT NULL,
`minutes` int(11) NOT NULL DEFAULT '0',
`status` varchar(16) NOT NULL,
`remarks` varchar(512) NOT NULL,
PRIMARY KEY (`id`),
KEY `pcode` (`pcode`),
KEY `team_1` (`team_1`),
KEY `team_2` (`team_2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
CREATE TABLE IF NOT EXISTS `football_teams` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pcode` varchar(32) NOT NULL,
`name` varchar(32) NOT NULL,
`shortname` varchar(32) DEFAULT NULL,
`played` int(11) NOT NULL,
`won` int(11) NOT NULL,
`draw` int(11) NOT NULL,
`lost` int(11) NOT NULL,
`points` int(11) NOT NULL,
`previous_results` varchar(16) NOT NULL,
`remarks` varchar(512) NOT NULL,
PRIMARY KEY (`id`),
KEY `pcode` (`pcode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
--
-- Constraints for table `football_goals`
--
ALTER TABLE `football_goals`
ADD CONSTRAINT `football_goals_ibfk_1` FOREIGN KEY (`match`) REFERENCES `football_matches` (`id`),
ADD CONSTRAINT `football_goals_ibfk_2` FOREIGN KEY (`team`) REFERENCES `football_teams` (`id`);
--
-- Constraints for table `football_matches`
--
ALTER TABLE `football_matches`
ADD CONSTRAINT `football_matches_ibfk_1` FOREIGN KEY (`pcode`) REFERENCES `football_league` (`code`),
ADD CONSTRAINT `football_matches_ibfk_2` FOREIGN KEY (`team_1`) REFERENCES `football_teams` (`id`),
ADD CONSTRAINT `football_matches_ibfk_3` FOREIGN KEY (`team_2`) REFERENCES `football_teams` (`id`);
--
-- Constraints for table `football_teams`
--
ALTER TABLE `football_teams`
ADD CONSTRAINT `football_teams_ibfk_1` FOREIGN KEY (`pcode`) REFERENCES `football_league` (`code`);
INSERT INTO `football_league` (`id`, `league`, `country`, `code`) VALUES
(1, 'International', 'International', 'L001'),
(2, 'English Premier League', 'English', 'L002'),
(3, 'Scottish Premier League', 'Scotland', 'L003');
INSERT INTO `football_matches` (`id`, `pcode`, `date`, `time`, `team_1`, `team_2`, `minutes`, `status`, `remarks`) VALUES
(1, 'L001', '2015-07-06', '18:45:00', 1, 2, 0, 'running', '18:00'),
(2, 'L002', '2015-07-02', '18:00:00', 7, 8, 0, 'FT', ''),
(3, 'L001', '2015-07-06', '18:45:00', 1, 2, 22, 'running', '');
INSERT INTO `football_teams` (`id`, `pcode`, `name`, `shortname`, `played`, `won`, `draw`, `lost`, `points`, `previous_results`, `remarks`) VALUES
(1, 'L002', 'Arsenal', 'arsenal', 50, 30, 10, 10, 70, 'WWLLD', ''),
(2, 'L002', 'Chelsea', 'chelsea', 50, 20, 10, 20, 50, 'LLWWW', ''),
(6, 'L002', 'Manchester City', 'manchester', 30, 20, 3, 7, 60, 'WWWWW', ''),
(7, 'L001', 'England', 'england', 50, 20, 13, 17, 53, 'WLWLL', ''),
(8, 'L001', 'Brazil', 'brazil', 30, 22, 2, 6, 46, 'WLLWW', ''),
(9, 'L001', 'France', 'france', 36, 18, 10, 8, 46, 'LLLWW', '');
INSERT INTO `football_goals` (`id`, `match`, `team`, `goals`, `time`) VALUES
(1, 1, 1, 1, '2015-07-06 14:36:00'),
(2, 1, 2, 1, '2015-07-06 12:28:00'),
(3, 2, 7, 1, '2015-07-06 14:39:00'),
(4, 2, 8, 1, '2015-07-06 12:28:00'),
(6, 1, 1, 1, '2015-07-06 08:33:00');
I want to write a SQL statement, which will show all the matches with score by particular league and date. I have tried to write the below SQL:
SELECT
football_league.code, football_matches.id,
football_league.league, football_league.country,
football_matches.date, football_matches.time as match_time,
football_matches.team_1, ft_1.name as name_a,
ft_1.shortname as short_a,
football_matches.team_2, ft_2.name as name_b,
ft_2.shortname as short_b,
football_matches.minutes, football_matches.status, football_matches.remarks,
sum(fg_1.goals) as score_a,
sum(fg_2.goals) as score_b
FROM football_matches
INNER JOIN football_teams as ft_1
ON ft_1.id = football_matches.team_1
INNER JOIN football_teams as ft_2
ON ft_2.id = football_matches.team_2
INNER JOIN football_league
ON football_league.code = football_matches.pcode
LEFT JOIN football_goals as fg_1
ON `fg_1`.`match` = football_matches.id AND `fg_1`.`team` = ft_1.id
LEFT JOIN football_goals as fg_2
ON `fg_2`.`match` = football_matches.id AND `fg_2`.`team` = ft_2.id
WHERE
football_league.code = 'L001'
AND
football_matches.date = '2015-07-06'
My problem is:
i) The score showing wrong, it should be 2-1, instead it's showing 2-2
ii) Second problem is I also need to show other matches also, where no team scored a goal, which is not showing, I tried with LEFT JOIN, but it still not showing other matches.
Try following:
SELECT
football_league.code, football_matches.id,
football_league.league, football_league.country,
football_matches.date, football_matches.time as match_time,
football_matches.team_1, ft_1.name as name_a,
ft_1.shortname as short_a,
football_matches.team_2, ft_2.name as name_b,
ft_2.shortname as short_b,
football_matches.minutes, football_matches.status, football_matches.remarks,
(SELECT sum(goals) FROM football_goals WHERE `match` = football_matches.id AND `team` = ft_1.id) as 'score1',
(SELECT sum(goals) FROM football_goals WHERE `match` = football_matches.id AND `team` = ft_2.id) as 'score2'
FROM football_matches
INNER JOIN football_teams as ft_1
ON ft_1.id = football_matches.team_1
INNER JOIN football_teams as ft_2
ON ft_2.id = football_matches.team_2
INNER JOIN football_league
ON football_league.code = football_matches.pcode
LEFT JOIN football_goals as fg_1
ON `fg_1`.`match` = football_matches.id AND `fg_1`.`team` = ft_1.id
LEFT JOIN football_goals as fg_2
ON `fg_2`.`match` = football_matches.id AND `fg_2`.`team` = ft_2.id
WHERE
football_league.code = 'L001'
AND
football_matches.date = '2015-07-06'
GROUP BY football_matches.id

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

MySQL statement to find data in two tables

I suck at doing joins in MySQL, and I'm pretty sure this is what I need to make this work (though correct me if I'm wrong).
So I have two tables. Here's the SQL to set-up a simple database:
CREATE TABLE IF NOT EXISTS `wp_usermeta` (
`umeta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`meta_key` varchar(255) DEFAULT NULL,
`meta_value` longtext,
PRIMARY KEY (`umeta_id`),
KEY `user_id` (`user_id`),
KEY `meta_key` (`meta_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES
(1, 1, 'first_name', 'David'),
(2, 1, 'last_name', 'Jones'),
(3, 1, 'nickname', 'david'),
(4, 1, 'newsletter', '1'),
(5, 2, 'first_name', 'Greg'),
(6, 2, 'last_name', 'Smith'),
(7, 2, 'nickname', 'greg'),
(8, 2, 'newsletter', '0');
CREATE TABLE IF NOT EXISTS `wp_users` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_login` varchar(60) NOT NULL DEFAULT '',
`user_pass` varchar(64) NOT NULL DEFAULT '',
`user_nicename` varchar(50) NOT NULL DEFAULT '',
`user_email` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`ID`),
KEY `user_login_key` (`user_login`),
KEY `user_nicename` (`user_nicename`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`) VALUES
(1, 'david', '$^*#NNR&Y&)Mn9emfdfsdfsdfsd', 'david', 'david#domain.com'),
(2, 'greg', 'fdfsdfsdfsd$^*#NNR&Y&)Mn9em', 'greg', 'greg#domain.com');
...and I need to write a statement for a basic page that simply finds the users who have subscribed to the newsletter (meta_key with a meta_value of 1) and displays their first_name and user_email.
Thanks in advance.
It takes a fairly simple join;
SELECT user_login FROM wp_users
JOIN wp_usermeta
ON wp_users.id=wp_usermeta.user_id
WHERE meta_key='newsletter'
AND meta_value=1;
SQLfiddle to play with.