Calculate value based on sub squery in Trigger - mysql

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

Related

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

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.

right join query returning null value records

CREATE TABLE IF NOT EXISTS `tweets_comment_tbl` (
`tweet_comment_id` int(12) NOT NULL AUTO_INCREMENT,
`tweet_id` int(12) NOT NULL,
`tweets_comment` text NOT NULL,
`created` int(12) NOT NULL,
`changed` int(12) NOT NULL,
`uid` int(12) NOT NULL,
`userip` varchar(20) NOT NULL,
`referer` text NOT NULL,
`status` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`tweet_comment_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `tweets_comment_tbl`
--
INSERT INTO `tweets_comment_tbl` (`tweet_comment_id`, `tweet_id`, `tweets_comment`, `created`, `changed`, `uid`, `userip`, `referer`, `status`) VALUES
(1, 1, 'COMMENT USER1', 1319395671, 1319395671, 3, '127.0.0.1', 'http://localhost/drupal_tutorial/', 1),
(2, 2, 'comment admin user', 1319395724, 1319395724, 1, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1),
(3, 2, 'USER COMMENTING HIS COMMENT', 1319395838, 1319395838, 3, '127.0.0.1', 'http://localhost/drupal_tutorial/', 1),
(4, 2, 'ADMIN COMMENTING FOR HIS COMMENT', 1319395865, 1319395865, 1, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1),
(5, 2, 'dddCOMMENT USER1: ADMIN DOING COMMENT FOR STATUS UPDATE1', 1319395905, 1319395905, 1, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1);
my second table
CREATE TABLE IF NOT EXISTS `tweets_tbl` (
`tweet_id` int(11) NOT NULL AUTO_INCREMENT,
`tweets` text NOT NULL,
`created` int(12) NOT NULL,
`changed` int(12) NOT NULL,
`uid` int(12) NOT NULL,
`userip` varchar(20) NOT NULL,
`referer` text NOT NULL,
`status` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`tweet_id`),
KEY `tweet_id` (`tweet_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `tweets_tbl`
--
INSERT INTO `tweets_tbl` (`tweet_id`, `tweets`, `created`, `changed`, `uid`, `userip`, `referer`, `status`) VALUES
(1, 'STATUS UPDATE 1', 1319395633, 1319395633, 1, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1),
(2, 'Status update user1', 1319395696, 1319395696, 3, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1);
Trying join query
SELECT ut.picture as picture, tct.tweet_id as tweet_id, tct.tweets_comment as tweets_comment, tct.changed
FROM tweets_comment_tbl tct
RIGHT JOIN users as ut ON tct.uid=ut.uid AND tct.tweet_id=2 AND tct.status = 1
order by tct.created desc
return records for above query
picture tweet_id tweets_comment changed
1 COMMENT USER1 1319395671
NULL NULL NULL
picture-1.png NULL NULL NULL
actually what i expected is
picture tweet_id tweets_comment changed
1 COMMENT USER1 1319395671
Why query has been returning NULL records, i am not sure where i made mistake in join query.
The query returns all rows from users and joins tweets_comment_tbl based on condition in ON. If no records in tweets_comment_tbl matches userid, the record from users still included into recordset. You probably need INNER JOIN if you want to see just users with comments.
Side note :
I think it's almost always possible to avoid RIGHT JOIN; queries with LEFT JOIN are much easier to read and understand.

Dynamic Foreign Keys - How To Implement?

I have 4 tables (appointed, class, elected, status) that I want to cross reference into a single table's (members) column. The values of the of 4 tables are time sensitive based off a history table (members_history). The desired result is that the query should output all members and the current appointed position or current elected position, class, and status within the members row and include additional information obtained from the foreign rows.
So instead of just returning:
id, username, password, salt, name_first, name_last, date_join & date_leave;
The query would return
id, username, password, salt, name_prefix, name_first, name_last, hours_extra, date_join, date_leave, appointed, class, elected & status;
Wherever an added column does not have a current value in history it's result should be NULL.
Now I think I can do this with sub-querys, but have been so far banging my head against the keyboard. I'll take another swing at it later, but until then, anyone else willing to give it a shot, or attempt to point me in the right direction?
The structure of my SQL (no pun intended) tables is as follows:
CREATE TABLE IF NOT EXISTS `members` (
`id` mediumint(3) unsigned NOT NULL auto_increment COMMENT 'Members Unique Id',
`username` varchar(32) collate utf8_bin NOT NULL COMMENT 'Mebers Username',
`password` varchar(64) collate utf8_bin NOT NULL COMMENT 'Members Password Hash',
`salt` varchar(32) collate utf8_bin NOT NULL COMMENT 'Members Password Salt',
`name_first` varchar(32) collate utf8_bin NOT NULL COMMENT 'Members First Name',
`name_last` varchar(32) collate utf8_bin NOT NULL COMMENT 'Members Last Name',
`date_join` date NOT NULL COMMENT 'Members Join Date',
`date_leave` date default NULL COMMENT 'Members Resgination Date (If Applicable)',
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Members id in this table = mid in other tables';
CREATE TABLE IF NOT EXISTS `members:apointed` (
`id` tinyint(3) unsigned NOT NULL auto_increment COMMENT 'Unique value',
`name_prefix` varchar(8) collate utf8_bin NOT NULL COMMENT 'Prefix Added to Members Name',
`hours_extra` decimal(4,2) NOT NULL COMMENT 'Hours Given as Bonus for Holding this Position.',
`position` varchar(40) collate utf8_bin NOT NULL COMMENT 'Name of the Posisiton',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Undefined within the SOP or By-Laws.';
CREATE TABLE IF NOT EXISTS `members:class` (
`id` tinyint(3) unsigned NOT NULL auto_increment COMMENT 'Unique Id',
`class` varchar(8) collate utf8_bin NOT NULL COMMENT 'Unique Value',
PRIMARY KEY (`id`),
UNIQUE KEY `value` (`class`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Article I, Section 1 Subsection B: Classes of Membership';
CREATE TABLE IF NOT EXISTS `members:elected` (
`id` tinyint(3) unsigned NOT NULL auto_increment COMMENT 'Unique value',
`name_prefix` varchar(8) collate utf8_bin NOT NULL COMMENT 'Prefix Added to Members Name',
`hours_extra` decimal(4,2) NOT NULL COMMENT 'Hours Given as Bonus for Holding this Position.',
`position` varchar(40) collate utf8_bin NOT NULL COMMENT 'Name of the Posisiton',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Article II';
CREATE TABLE IF NOT EXISTS `members:status` (
`id` tinyint(3) unsigned NOT NULL auto_increment COMMENT 'Bit''s Place',
`status` varchar(16) collate utf8_bin NOT NULL COMMENT 'Categorie''s Name',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Article I, Section 1, Subsection A: Categories of Membership';
CREATE TABLE IF NOT EXISTS `members_history` (
`id` int(10) unsigned NOT NULL auto_increment COMMENT 'Unique Id',
`mid` tinyint(3) unsigned NOT NULL COMMENT 'Members Unique Id.',
`table` enum('class','elected','appointed','status') NOT NULL COMMENT 'Name of Table that was Edited.',
`value` tinyint(3) unsigned NOT NULL COMMENT 'Value',
`start` date NOT NULL COMMENT 'Value''s Effect Date',
`end` date default NULL COMMENT 'Value''s Expiration Date',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Member History';
members_history.mid is a FK for id in the members table, not every member will have history on them (but eventually they all will, as every member will have to have a class and status). members_history.value is a FK for members:{members_history.table}.id;
INSERT INTO `members`
(`id`, `username`, `password`, `salt`, `name_first`, `name_last`, `date_join`, `date_join`) VALUES
( 1, 'Dygear',MD5('pass'), 's417', 'Mark', 'Tomlin', DATE(), NULL),
( 2, 'uberusr',MD5('p455'), '235f', 'Howard', 'Singer', DATE(), NULL),
( 3,'kingchief',MD5('leet'), '32fs','Christopher', 'Buckham', DATE(), NULL);
INSERT INTO `members:apointed`
(`id`, `name_prefix`, `hours_extra`, `posisiton`) VALUES
( 1, '', 0.00, 'Crew Chief'),
( 2, '', 20.00, 'Engineer'),
( 3, 'Lt.', 40.00, 'Lieutenant'),
( 4, 'Capt.', 60.00, 'Captin'),
( 5, 'Chief.', 80.00, '3rd Assistant Chief of Operation');
INSERT INTO `members:class`
(`id`, `class`) VALUES
( 1, 'Class I'),
( 2, 'Class II');
INSERT INTO `members:elected`
(`id`, `name_prefix`, `hours_extra`, `posisiton`) VALUES
( 1, '', 40.00, 'Trustee'),
( 2, '', 40.00, 'Chairman of the Board'),
( 3, 'Prez.', 40.00, 'President'),
( 4, 'VPrez.', 40.00, 'Vice-President'),
( 5, '', 40.00, 'Recording Secretary'),
( 6, '', 40.00, 'Service Secretary'),
( 7, '', 40.00, 'Corresponding Secretary'),
( 8, '', 40.00, 'Financial Secretary Treasuer'),
( 9, '', 40.00, 'Assistant Financial Secretary Treasuer'),
( 10, 'Chief.', 80.00, 'Chief of Operations'),
( 11, 'Chief.', 80.00, 'First Deputy Chief of Operations'),
( 12, 'Chief.', 80.00, 'Second Deputy Chief of Operation');
INSERT INTO `members:status`
(`id`, `status`) VALUES
( 1, 'Active'),
( 2, 'Inactive'),
( 3, 'Student'),
( 4, 'Probationary'),
( 5, 'Lifetime'),
( 6, 'Cadet'),
( 7, 'Honorary'),
( 8, 'Medical'),
( 9, 'Military'),
( 10, 'Resigned'),
( 11, 'Disvowed');
INSERT INTO `members_history`
(`id`, `mid`, `table`, `value`, `start`, `end`) VALUES
(NULL, 1, 'apointed', 3, DATE(), NULL),
(NULL, 1, 'class', 1, DATE(), NULL),
(NULL, 1, 'status', 1, DATE(), NULL),
(NULL, 2, 'elected', 4, DATE(), NULL),
(NULL, 2, 'class', 1, DATE(), NULL),
(NULL, 2, 'status', 1, DATE(), NULL),
(NULL, 3, 'apointed', 10, DATE(), '2010-05-01'),
(NULL, 3, 'class', 1, DATE(), NULL),
(NULL, 3, 'status', 1, DATE(), NULL);
You're using a design called polymorphic associations and it's frequently done wrong. The way to make it work is to create another table, say members:abstract:
CREATE TABLE IF NOT EXISTS `members:abstract` (
`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`type` enum('class','elected','appointed','status') NOT NULL,
UNIQUE KEY (`id`, `type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
This table serves as the parent table for all of your members attributes tables. Each of these tables changes its primary key to not generate id values automatically, but instead reference the primary key of members:abstract. I'll show just members:appointed but the others would be similar.
CREATE TABLE IF NOT EXISTS `members:appointed` (
`id` INT UNSIGNED NOT NULL PRIMARY KEY, -- not auto_increment
`name_prefix` varchar(8) collate utf8_bin NOT NULL COMMENT 'Prefix Added to Members Name',
`hours_extra` decimal(4,2) NOT NULL COMMENT 'Hours Given as Bonus for Holding this Position.',
`position` varchar(40) collate utf8_bin NOT NULL COMMENT 'Name of the Posisiton',
FOREIGN KEY (`id`) REFERENCES `members:abstract` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Undefined within the SOP or By-Laws.';
You can make this table gain auto-generated values automatically with a trigger:
DELIMITER //
DROP TRIGGER IF EXISTS ins_appointed//
CREATE TRIGGER ins_appointed BEFORE INSERT ON `members:appointed`
FOR EACH ROW BEGIN
INSERT INTO `members:abstract` (`type`) VALUES ('appointed');
SET NEW.id = LAST_INSERT_ID();
END; //
DELIMITER ;
Do the same for each of the other attribute tables.
Note that the id values are now unique across all your attribute tables.
Next you make members:abstract the target for a foreign key in members_history.
CREATE TABLE IF NOT EXISTS `members_history` (
`id` INT unsigned NOT NULL auto_increment COMMENT 'Unique Id',
`mid` INT unsigned NOT NULL COMMENT 'Members Unique Id.',
`value` INT UNSIGNED NOT NULL,
`table` enum('class','elected','appointed','status') NOT NULL,
`start` date NOT NULL COMMENT 'Value''s Effect Date',
`end` date default NULL COMMENT 'Value''s Expiration Date',
PRIMARY KEY (`id`),
FOREIGN KEY (`mid`) REFERENCES `members` (`id`) ON DELETE CASCADE,
FOREIGN KEY (`value`, `table`) REFERENCES `members:abstract` (`id`, `type`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Member History';
Notice that this table defines a foreign key so that you can't reference an id of the wrong type of attribute in members:abstract.
Now you can rely on referential integrity and consistency which is impossible when you try to implement polymorphic associations without the common parent of all the referenced attribute tables.
Here's the query that returns the result you described (tested on MySQL 5.1.40):
SELECT m.username,
m.password, m.salt, m.name_first, m.name_last,
MAX(a.name_prefix) AS name_prefix,
COALESCE(MAX(a.hours_extra), MAX(e.hours_extra)) AS hours_extra,
MAX(m.date_join) AS date_join,
MAX(m.date_leave) AS date_leave,
MAX(a.position) AS appointed,
MAX(c.class) AS class,
MAX(e.position) AS elected,
MAX(s.status) AS status
FROM `members` m
JOIN `members_history` h ON (h.mid = m.id)
LEFT OUTER JOIN `members:appointed` a ON (h.table = 'appointed' AND h.value = a.id)
LEFT OUTER JOIN `members:class` c ON (h.table = 'class' AND h.value = c.id)
LEFT OUTER JOIN `members:elected` e ON (h.table = 'elected' AND h.value = e.id)
LEFT OUTER JOIN `members:status` s ON (h.table = 'status' AND h.value = s.id)
GROUP BY m.id;
all you need is a left outer join for each of the history types and whatever logic you need to pick the "current" row.
your table structure doesn't quite make enough sense to me to put together a sample for you. maybe if you provide ONE sample member and a couple of rows of history for ONE attribute, i can help you out.