MySQL statement to find data in two tables - mysql

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.

Related

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

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

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.