SQL issues in JOIN statement - mysql

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

Related

SQL sorted by a diferent fields

I have the next tables and rows. And I need to write a SELECT that returns all categories sorted by:
(A) the number of items they have
and (B) the category name.
This query should fetch the following columns: the category name, the number of items (AS N_ITEMS) and the average price of the titles in that category (AS AVERAGE_PRICE)
CREATE TABLE `category` (
`CATEGORY_ID` int(11) NOT NULL,
`CATEGORY_NAME` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `category` (`CATEGORY_ID`, `CATEGORY_NAME`) VALUES
(1, 'Sports'),
(2, 'Actualités'),
(3, 'Animaux'),
(4, 'Economie'),
(5, 'Cuisine');
CREATE TABLE `item` (
`ITEM_ID` int(11) NOT NULL,
`CATEGORY_ID` int(11) NOT NULL,
`ITEM_NAME` varchar(50) NOT NULL,
`ITEM_PRICE` decimal(8,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `item` (`ITEM_ID`, `CATEGORY_ID`, `ITEM_NAME`, `ITEM_PRICE`) VALUES
(1, 1, 'Equip', '6.00'),
(2, 2, 'Le Monde', '3.00'),
(3, 2, 'Le Parisien', '2.50'),
(4, 2, 'France soir', '3.00'),
(5, 3, '30 Million damis', '6.20'),
(6, 3, 'Cheval pratique', '4.50'),
(7, 4, 'Capital', '2.50');
ALTER TABLE `category`
ADD PRIMARY KEY (`CATEGORY_ID`);
ALTER TABLE `item`
ADD PRIMARY KEY (`ITEM_ID`);
ALTER TABLE `category`
MODIFY `CATEGORY_ID` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `item`
MODIFY `ITEM_ID` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
You can try below -
select CATEGORY_NAME, count(ITEM_ID) as noofItem,avg(item_price) as avgprice
from category inner join item on category.category_id=item.category_id
group by CATEGORY_NAME
order by noofItem,CATEGORY_NAME

multiple sum in my sql

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

Calculate value based on sub squery in Trigger

I want to create a trigger in MySql to insert some values in table A and if the record already exist I want to re-calculate one of the fields but I'm keep getting a syntax error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'P1
INNER JOIN
(
SELECT SUM(ATS) AS TOTAGAINST, TOURNID, HOMETEAM, ROUNDID' at line 6
Here's my code (stripped for debugging):
DROP TRIGGER IF EXISTS `trig_matches_insert`;
DELIMITER //
CREATE TRIGGER `trig_matches_insert` AFTER INSERT ON `matches`
FOR EACH ROW
BEGIN
INSERT INTO positions (TEAMID, SC_AGAINST, SC_FOR, ROUNDID, TOURNID) values
(new.HOMETEAM, new.ATS, new.HTS, new.ROUNDID, new.TOURNID)
ON DUPLICATE KEY
UPDATE positions P1
INNER JOIN
(
SELECT SUM(ATS) AS TOTAGAINST, TOURNID, HOMETEAM, ROUNDID FROM matches GROUP BY
TOURNID,HOMETEAM, ROUNDID
) P2 ON P2.HOMETEAM = P1.TEAMID AND P2.TOURNID = P1.TOURNID AND P2.ROUNDID = P1.ROUNDID
SET P1.SC_AGAINST = P2.TOTAGAINST WHERE P1.ID = 10;
END
//
DELIMITER ;
I can't tell what's wrong here..
When I run the update query stand-alone it runs fine
Here's some supporting sql:
CREATE TABLE IF NOT EXISTS `matches` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TOURNID` int(11) NOT NULL,
`HOMETEAM` int(11) NOT NULL,
`AWAYTEAM` int(11) NOT NULL,
`HTS` decimal(10,0) NOT NULL,
`ATS` decimal(10,0) NOT NULL,
`FIELD` text NOT NULL,
`TIME` datetime NOT NULL,
`ROUNDID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `TOURNID` (`TOURNID`),
KEY `HOMETEAM` (`HOMETEAM`),
KEY `AWAYTEAM` (`AWAYTEAM`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;
INSERT INTO `matches` (`ID`, `TOURNID`, `HOMETEAM`, `AWAYTEAM`, `HTS`, `ATS`, `FIELD`, `TIME`, `ROUNDID`) VALUES
(17, 1, 30, 31, '2', '3', '', '2015-01-04 00:00:00', 1),
(18, 1, 30, 3, '2', '4', '', '2015-01-04 00:00:00', 1),
(19, 1, 30, 4, '3', '5', '', '2015-01-04 00:00:00', 1);
CREATE TABLE IF NOT EXISTS `positions` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TOURNID` int(11) NOT NULL,
`TEAMID` int(11) NOT NULL,
`ROUNDID` int(11) NOT NULL,
`SC_FOR` decimal(10,0) NOT NULL,
`SC_AGAINST` decimal(10,0) NOT NULL,
`POULEID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `TOURNID_2` (`TOURNID`,`TEAMID`,`ROUNDID`),
KEY `TOURNID` (`TOURNID`,`TEAMID`),
KEY `TEAMID` (`TEAMID`),
KEY `ROUND` (`ROUNDID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;
INSERT INTO `positions` (`ID`, `TOURNID`, `TEAMID`, `ROUNDID`, `SC_FOR`, `SC_AGAINST`, `POULEID`) VALUES
(10, 1, 30, 1, '2', '12', 0);
Thanks in advance
Mike
Think I've found it, looks like after ON DUPLICATE KEY the positions table already got scope no need to build and update statement from scratch, seems like a quick select will do just fine:
DROP TRIGGER IF EXISTS `matches_after_ins_trig`;
DELIMITER //
CREATE TRIGGER `matches_after_ins_trig` AFTER INSERT ON `matches`
FOR EACH ROW
BEGIN
INSERT INTO positions (TEAMID, SC_AGAINST, SC_FOR, ROUNDID, TOURNID) values (new.HOMETEAM, new.ATS, new.HTS, new.ROUNDID, new.TOURNID)
ON DUPLICATE KEY UPDATE SC_AGAINST = (SELECT SUM(ATS) FROM matches WHERE
matches.HOMETEAM = new.HOMETEAM AND matches.TOURNID = new.TOURNID AND
matches.ROUNDID = new.ROUNDID GROUP BY TOURNID,HOMETEAM, ROUNDID);
END

MySQL Query - How do I get a SUM with GROUP BY and WHERE condition and use LEFT OUTER JOIN?

I'm not sure how to get the result that I expect and I've tried everything. I also need to be able to get the expected results using one query.
Here are the two tables with some sample data:
--
-- Table structure for table `accounts`
--
CREATE TABLE IF NOT EXISTS `accounts` (
`id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`type_id` int(11) NOT NULL,
`description` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Data for table `accounts`
--
INSERT INTO `accounts` (`id`, `name`, `type_id`, `description`) VALUES
(100, 'DUES', 0, NULL),
(101, 'NET WEEKLY PAYROLL', 0, NULL),
(111, 'FEDERAL TAX DEPOSITS', 0, 'tax stuff'),
(113, 'UNITED ASSOCIATION PAYMENTS', 0, NULL),
(114, 'OFFICERS MEETING ALLOWANCES', 0, NULL);
--
-- Table structure for table `checks`
--
CREATE TABLE IF NOT EXISTS `checks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`batch_id` int(11) DEFAULT NULL,
`entry_date` date NOT NULL,
`account_id` int(11) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`description` varchar(200) DEFAULT NULL,
`posted` tinyint(4) NOT NULL DEFAULT '0',
`vendor_id` int(11) DEFAULT NULL,
`check_num` int(11) NOT NULL,
`voided` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `checks`
--
INSERT INTO `checks` (`id`, `batch_id`, `entry_date`, `account_id`, `amount`, `description`, `posted`, `vendor_id`, `check_num`, `voided`) VALUES
(1, NULL, '2013-01-21', 111, '77.44', 'Last Year', 0, 1, 100, 0),
(2, NULL, '2014-01-21', 111, '521.11', 'Test Stuff', 0, 1, 101, 0),
(3, NULL, '2014-01-20', 101, '121.11', 'More Tests', 0, 1, 222, 0),
(4, NULL, '2014-01-02', 101, '150.00', 'test', 0, 4, 213, 0);
I want to create a list of all accounts with a month-to-date sum as an added field. Here is the query to get the month-to-date sum without joining the accounts table:
SELECT *, SUM(amount) as mtd FROM `checks` WHERE `entry_date` > '2014-01-01' GROUP BY `account_id`
... and here is what i used to get all the accounts joined to checks table:
SELECT * FROM `accounts` LEFT OUTER JOIN `checks` ON `checks.account_id` = `accounts.id`
I just can't seem to combine these two correctly to get the expected results. Please help!
I think this solves your problem:
SELECT a.*, SUM(c.amount) as mtd
FROM accounts a left outer join
checks c
ON (a.id = c.account_id) and c.entry_date >= '2014-01-01'
GROUP BY a.account_id;
This will return all accounts, even those with no activity in January. I changed the date condition to >=, because that "feels" better as a month-to-date cutoff.

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