MySQL - Return columns based on value - mysql

I need to retrieve data from a database and I have no way to change its structure.
There are 3 distinct fields for address:
Personal: client_address_1, client_address_2, client_address_3, client_address_4
Postal: client_postaladdress_1, client_postaladdress_2, client_postaladdress_3, client_postaladdress_4
Company: client_company_address_1, client_company_address_2, client_company_address_3, client_company_address_4
and one field (client_prefered_address) which contains in which address the client wants to receive his correspondence.
From them I need to retrieve the address of choice, so, if the client is marked as postal, it should return the columns: client_postaladdress_1, client_postaladdress_2, client_postaladdress_3, client_postaladdress_4 but not the others.
Is there any way to do it? I have been Googling for two days.
Thanks
SQL:
CREATE TABLE IF NOT EXISTS `client` (
`client_id` int(11) NOT NULL AUTO_INCREMENT,
`client_address_1` varchar(255) COLLATE utf8_bin NOT NULL,
`client_address_2` varchar(255) COLLATE utf8_bin NOT NULL,
`client_address_3` varchar(255) COLLATE utf8_bin NOT NULL,
`client_address_4` varchar(255) COLLATE utf8_bin NOT NULL,
`client_postaladdress_1` varchar(255) COLLATE utf8_bin NOT NULL,
`client_postaladdress_2` varchar(255) COLLATE utf8_bin NOT NULL,
`client_postaladdress_3` varchar(255) COLLATE utf8_bin NOT NULL,
`client_postaladdress_4` varchar(255) COLLATE utf8_bin NOT NULL,
`client_company_address_1` varchar(255) COLLATE utf8_bin NOT NULL,
`client_company_address_2` varchar(255) COLLATE utf8_bin NOT NULL,
`client_company_address_3` varchar(255) COLLATE utf8_bin NOT NULL,
`client_company_address_4` varchar(255) COLLATE utf8_bin NOT NULL,
`client_prefered_address` char(10) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`client_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=4;
--
-- Dumping data for table `client`
--
INSERT INTO `client` (`client_id`, `client_address_1`, `client_address_2`, `client_address_3`, `client_address_4`, `client_postaladdress_1`, `client_postaladdress_2`, `client_postaladdress_3`, `client_postaladdress_4`, `client_company_address_1`, `client_company_address_2`, `client_company_address_3`, `client_company_address_4`, `client_prefered_address`) VALUES
(1, 'Yellow house', 'Yellow street, 25', '09090 Yellow city', 'Yellow Country', 'Blue postbox', 'Blue avenue, 90', '09039 Blue city', 'Blue Country', 'Green house', 'Green street, 100', '02930 Green city', 'Green Country', 'Postal'),
(2, 'Apple house', 'Apple street, 200', 'Apple State 2039', 'Apple Land', 'Melon House', 'Melon Boulevard ', 'Melon State ', 'Melon Land', '', '', '', '', 'Personal'),
(3, '', '', '', '', '', '', '', '', 'Chocolate Factory', 'Charlie street 293', 'Chocolate CH', 'Chocolate Kingdom ', 'Company');

Try this with CASE
select
(CASE WHEN client_prefered_address ='Postal'
THEN client_postaladdress_1
WHEN client_prefered_address ='Personal' THEN client_address_1
WHEN client_prefered_address ='Company' THEN client_company_address_1
ELSE NULL END) `addressone`
,
(CASE WHEN client_prefered_address ='Postal'
THEN client_postaladdress_2
WHEN client_prefered_address ='Personal' THEN client_address_2
WHEN client_prefered_address ='Company' THEN client_company_address_2
ELSE NULL END) `addresstwo`,
(CASE WHEN client_prefered_address ='Postal'
THEN client_postaladdress_3
WHEN client_prefered_address ='Personal' THEN client_address_3
WHEN client_prefered_address ='Company' THEN client_company_address_3
ELSE NULL END) `addressthree`,
(CASE WHEN client_prefered_address ='Postal'
THEN client_postaladdress_4
WHEN client_prefered_address ='Personal' THEN client_address_4
WHEN client_prefered_address ='Company' THEN client_company_address_4
ELSE NULL END) `addressfour`
FROM `client`
FIDDLE

I suggest using 2 queries to solve this. One to get the preferred address, and another to get the correct fields. Use whatever programming language you are using to generte the 2nd query with the right fields.
If you really want to use MySQL, you can use the CASE statement (it's like a switch):
SELECT client_id, (
CASE client_prefered_address
WHEN 'Postal' THEN client_postaladdress_1
WHEN 'Personal' THEN client_address_1
WHEN 'Company' THEN client_company_address_1
END) AS address_1, (
CASE client_prefered_address
WHEN 'Postal' THEN client_postaladdress_2
WHEN 'Personal' THEN client_address_2
WHEN 'Company' THEN client_company_address_2
END) AS address_2, (
CASE client_prefered_address
WHEN 'Postal' THEN client_postaladdress_3
WHEN 'Personal' THEN client_address_3
WHEN 'Company' THEN client_company_address_3
END) AS address_3, (
CASE client_prefered_address
WHEN 'Postal' THEN client_postaladdress_4
WHEN 'Personal' THEN client_address_4
WHEN 'Company' THEN client_company_address_4
END) AS address_4
FROM client
DEMO: http://sqlfiddle.com/#!2/eab6b/3

Try something like this:
SELECT `client_id`,
IF(`client_prefered_address` = 'personal', `client_address_1`, IF(`client_prefered_address` = 'postal', `client_postaladdress_1`, `client_company_address_1`) AS `address_1`,
IF(`client_prefered_address` = 'personal', `client_address_2`, IF(`client_prefered_address` = 'postal', `client_postaladdress_2`, `client_company_address_2`) AS `address_2`,
IF(`client_prefered_address` = 'personal', `client_address_3`, IF(`client_prefered_address` = 'postal', `client_postaladdress_3`, `client_company_address_3`) AS `address_3`,
IF(`client_prefered_address` = 'personal', `client_address_4`, IF(`client_prefered_address` = 'postal', `client_postaladdress_4`, `client_company_address_4`) AS `address_4`
FROM `client`
WHERE blahblahblah

Related

LEFT JOIN select latest row from the left join

I have a company database that has all its details within it. It also has a separate table where credit ratings are stored.
DROP TABLE IF EXISTS `company`;
CREATE TABLE IF NOT EXISTS `company` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET latin1 NOT NULL,
`email` varchar(255) CHARACTER SET latin1 NOT NULL,
`address` varchar(255) NOT NULL,
`address2` text NOT NULL,
`address3` text NOT NULL,
`phone` text NOT NULL,
`contacts` text NOT NULL,
`islive` tinyint(1) NOT NULL DEFAULT '1',
`qt` tinyint(1) NOT NULL DEFAULT '30',
`pt` tinyint(1) NOT NULL DEFAULT '30',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `creditrating`;
CREATE TABLE IF NOT EXISTS `creditrating` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cid` int(11) NOT NULL,
`rating` int(11) NOT NULL,
`arating` varchar(10) NOT NULL,
`type` tinyint(1) NOT NULL DEFAULT '1',
`thedate` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `company` (`id`, `name`, `email`, `address`, `address2`, `address3`, `phone`, `contacts`, `islive`, `qt`, `pt`) VALUES
(190, 'Test Company', 'test#test.com', 'Testing Client 1\r\nsdfsdfsdf\r\nsdfsdfsdf', 'Testing Client 1\r\nsdfsdfsdf\r\nsdfsdfsdf', 'Testing Client 1\r\nsdfsdfsdf\r\nsdfsdfsdf', '65165156', 'test name', 1, 30, 30),
(191, 'Test Company 2', 'test2#test2.com', 'Testing Client 2\r\nsdfsdfsdf\r\nsdfsdfsdf', 'Testing Client 2\r\nsdfsdfsdf\r\nsdfsdfsdf', 'Testing Client 2\r\nsdfsdfsdf\r\nsdfsdfsdf', '65165156', 'test name 2', 1, 30, 30);
INSERT INTO `creditrating` (`id`, `cid`, `rating`, `arating`, `type`, `thedate`) VALUES
(3, 190, 684, 'da774', 1, '2021-03-30 15:08:52'),
(6, 190, 222, 'DD222', 1, '2021-03-30 17:46:22');
I am trying to only retrieve the company details and only the latest row on the credit rating table.
The SQL I have got closest to getting this to work is (Mysql 5.6):
SELECT c.id
, AES_DECRYPT(c.name, 'co1') as name
, AES_DECRYPT(c.phone, 'co3') as phone
, c.islive
, r.rating
FROM company c
LEFT
JOIN creditrating r
ON (SELECT r.thedate FROM creditrating WHERE c.id=r.cid ORDER BY r.thedate DESC LIMIT 1)
DB FIDDLE HERE
At the moment it is bringing back 2 rows of the same company instead of just 1.
Thank you in advance for any pointers you guys can through my way.
prior versions don't have window functions but you can switch to user defined variables
DROP TABLE IF EXISTS `company`;
CREATE TABLE IF NOT EXISTS `company` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET latin1 NOT NULL,
`email` varchar(255) CHARACTER SET latin1 NOT NULL,
`address` varchar(255) NOT NULL,
`address2` text NOT NULL,
`address3` text NOT NULL,
`phone` text NOT NULL,
`contacts` text NOT NULL,
`islive` tinyint(1) NOT NULL DEFAULT '1',
`qt` tinyint(1) NOT NULL DEFAULT '30',
`pt` tinyint(1) NOT NULL DEFAULT '30',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `creditrating`;
CREATE TABLE IF NOT EXISTS `creditrating` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cid` int(11) NOT NULL,
`rating` int(11) NOT NULL,
`arating` varchar(10) NOT NULL,
`type` tinyint(1) NOT NULL DEFAULT '1',
`thedate` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `company` (`id`, `name`, `email`, `address`, `address2`, `address3`, `phone`, `contacts`, `islive`, `qt`, `pt`) VALUES
(190, 'Test Company', 'test#test.com', 'Testing Client 1\r\nsdfsdfsdf\r\nsdfsdfsdf', 'Testing Client 1\r\nsdfsdfsdf\r\nsdfsdfsdf', 'Testing Client 1\r\nsdfsdfsdf\r\nsdfsdfsdf', '65165156', 'test name', 1, 30, 30),
(191, 'Test Company 2', 'test2#test2.com', 'Testing Client 2\r\nsdfsdfsdf\r\nsdfsdfsdf', 'Testing Client 2\r\nsdfsdfsdf\r\nsdfsdfsdf', 'Testing Client 2\r\nsdfsdfsdf\r\nsdfsdfsdf', '65165156', 'test name 2', 1, 30, 30);
INSERT INTO `creditrating` (`id`, `cid`, `rating`, `arating`, `type`, `thedate`) VALUES
(3, 190, 684, 'da774', 1, '2021-03-30 15:08:52'),
(6, 190, 222, 'DD222', 1, '2021-03-30 17:46:22');
SELECT
id, name, phone, islive, rating, `thedate`
FROM
(SELECT
name,
phone,
islive,
rating,
`thedate`,
IF(id = #id, #rnk:=#rnk + 1, #rnk:=1) AS rnk,
#id:=id AS id
FROM
(SELECT
c.id,
AES_DECRYPT(c.name, 'co1') AS name,
AES_DECRYPT(c.phone, 'co3') AS phone,
c.islive,
r.rating,
`thedate`
FROM
company c
LEFT JOIN creditrating r ON c.id = r.cid) t1, (SELECT #id:=- 1, #rnk:=0) t2
ORDER BY id , `thedate` DESC) t3
WHERE
rnk = 1;
id | name | phone | islive | rating | thedate
--: | :--- | :---- | -----: | -----: | :------------------
190 | null | null | 1 | 222 | 2021-03-30 17:46:22
191 | null | null | 1 | null | null
db<>fiddle here
You can use a window function for this:
SELECT c.id, AES_DECRYPT(c.name, 'co1') as name, AES_DECRYPT(c.phone, 'co3') as phone, c.islive, r.rating
FROM company c LEFT JOIN
(SELECT r.*,
ROW_NUMBER() OVER (PARTITION BY r.cid ORDER BY r.thedate DESC) as seqnum
FROM creditrating r
) r
ON c.id = r.cid AND r.seqnum = 1;

Selecting count from another table is only showing 1 row where it exists

I am trying to select a row count from another table even if it's empty, so if it's empty it just shows the number 0 but still selects the main table's rows.
Here's my sql:
SELECT training.*,
count(distinct training_transactions.training_transaction_course) as completed_training_payments
FROM training
INNER JOIN training_transactions
ON training.course_id = training_transactions.training_transaction_course
WHERE course_main = ?
AND course_enabled = 'enabled'
Training table:
CREATE TABLE IF NOT EXISTS `training` (
`course_id` int(11) NOT NULL,
`course_user` int(11) NOT NULL,
`course_main` int(11) NOT NULL,
`course_type` varchar(255) NOT NULL,
`course_name` varchar(255) NOT NULL,
`course_description` text NOT NULL,
`course_location` varchar(255) NOT NULL,
`course_duration` varchar(255) NOT NULL,
`course_fitness_type` varchar(255) NOT NULL,
`course_instructor_name` varchar(255) NOT NULL,
`course_price` int(15) NOT NULL,
`course_start_date` date NOT NULL,
`course_max_attendees` int(8) NOT NULL,
`course_accommodation` varchar(255) NOT NULL,
`course_accommodation_price` varchar(255) NOT NULL,
`course_status` varchar(50) NOT NULL,
`course_enabled` varchar(10) NOT NULL DEFAULT 'enabled',
`course_location_name` varchar(255) NOT NULL,
`course_location_street` varchar(255) NOT NULL,
`course_location_town` varchar(255) NOT NULL,
`course_location_county` varchar(255) NOT NULL,
`course_location_postcode` varchar(255) NOT NULL,
`course_location_country` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `training`
--
INSERT INTO `training` (`course_id`, `course_user`, `course_main`, `course_type`, `course_name`, `course_description`, `course_location`, `course_duration`, `course_fitness_type`, `course_instructor_name`, `course_price`, `course_start_date`, `course_max_attendees`, `course_accommodation`, `course_accommodation_price`, `course_status`, `course_enabled`, `course_location_name`, `course_location_street`, `course_location_town`, `course_location_county`, `course_location_postcode`, `course_location_country`) VALUES
(1, 3, 4, 'Health & Safety', 'lol', 'This is just a short description, this can be editted', '1', '13', 'lol', 'lol', 5, '1991-02-12', 4, '1', '4', 'live', 'enabled', '', '', '', '', '', 'United Kingdom'),
(2, 3, 4, 'Working at Height', 'lol', '', '1', '11', 'jkjkj', 'kjkjkj', 124, '0000-00-00', 6, '0', '', 'live', 'enabled', '', '123', '123', '123', 'WN8', 'United Kingdom'),
(3, 3, 4, 'Working at Height', 'lol', '', '1', '11', 'jkjkj', 'kjkjkj', 124, '0000-00-00', 6, '0', '', 'live', 'enabled', '', '123', '123', '123', 'WN8', 'United Kingdom');
training_transactions
CREATE TABLE IF NOT EXISTS `training_transactions` (
`training_transaction_id` int(11) NOT NULL,
`training_transaction_user` int(11) NOT NULL,
`training_transaction_course` int(11) NOT NULL,
`training_transaction_status` varchar(50) NOT NULL DEFAULT 'pending',
`training_transaction_payment_status` varchar(50) NOT NULL,
`training_transaction_cost` int(11) NOT NULL,
`training_transaction_enabled` varchar(50) NOT NULL DEFAULT 'enabled',
`training_transaction_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`training_transaction_billing_name` varchar(250) NOT NULL,
`training_transaction_billing_address1` varchar(250) NOT NULL,
`training_transaction_billing_address2` varchar(250) NOT NULL,
`training_transaction_billing_city` varchar(250) NOT NULL,
`training_transaction_billing_state` varchar(250) NOT NULL,
`training_transaction_billing_postcode` varchar(250) NOT NULL,
`training_transaction_billing_country` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `training_transactions`
--
INSERT INTO `training_transactions` (`training_transaction_id`, `training_transaction_user`, `training_transaction_course`, `training_transaction_status`, `training_transaction_payment_status`, `training_transaction_cost`, `training_transaction_enabled`, `training_transaction_date`, `training_transaction_billing_name`, `training_transaction_billing_address1`, `training_transaction_billing_address2`, `training_transaction_billing_city`, `training_transaction_billing_state`, `training_transaction_billing_postcode`, `training_transaction_billing_country`) VALUES
(1, 3, 1, 'pending', 'complete', 0, 'enabled', '2015-09-17 14:02:29', *removed my address*);
at the moment only the training course with id 1 is showing because a row in transactions exists how can I make all training display if it no id matches in the training_transactions?
Use LEFT JOIN instead of inner join to list all records from the table on the left of the join, plus you need to place the count() in a subquery to get all fields from the training table:
SELECT training.*, ifnull(T.transactioncount,0) as transactioncount
FROM training
LEFT JOIN (SELECT training_transaction_course, COUNT(training_transaction_course) as transactioncount FROM training_transactions GROUP BY training_transaction_course) AS T
ON training.course_id = T.training_transaction_course
WHERE course_main = ?
AND course_enabled = 'enabled'
INNER JOIN only selects records where records with join key in both tables exist.
With LEFT JOIN / RIGHT JOIN, selections can be made where records on one side don't exist; their field values will be NULL (and when counted, they should be zero but I'm not COMPLETELY sure of that)
Sometimes it is just easier to use sub-queries. Try this:
SELECT training.*,
(SELECT COUNT(distinct training_transactions.training_transaction_course)
FROM training_transactions
WHERE training.course_id = training_transactions.training_transaction_course) AS completed_training_payments
FROM training
WHERE training.course_main = ?
AND training.course_enabled = 'enabled'

Executing a SQL file

I am very new to MySQL. I have an SQL file called tables.sql as shown below.
I uploaded it to a subfolder in my public_html folder.
When I copy the below into a MySQL query and run it, I get this error: "Documentation #1046 - No database selected".
How can I execute this to create a table? When I go to http://mywebsite.com/subfolder/tables.sql it says Page not found
CREATE TABLE IF NOT EXISTS `users` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`fullname` varchar(200) NOT NULL,
`username` varchar(100) NOT NULL,
`email` varchar(200) NOT NULL,
`password` varchar(100) NOT NULL,
`gender` varchar(100) NOT NULL,
`photo` varchar(200) NOT NULL,
`businessname` text NOT NULL,
`telephone` varchar(200) NOT NULL,
`country` varchar(100) NOT NULL,
`confirmed` varchar(100) NOT NULL,
`registered_date` varchar(200) NOT NULL,
`last_visited` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
INSERT INTO `users` (`id`, `fullname`, `username`, `email`, `password`, `gender`, `photo`, `businessname`, `telephone`, `country`, `confirmed`, `registered_date`, `last_visited`) VALUES
(1, 'Vasplus Blog', 'vasplus', 'vasplusblog#gmail.com', '81dc9bdb52d04dc20036dbd8313ed055', 'Male', 'vasplus.gif', 'Vasplus Programming Blog', '', 'United States of America', 'yes', '05-05-2013', '05-05-2013'),
(2, 'Victor Olu', 'victor', 'vasplusblog#gmail.com', '81dc9bdb52d04dc20036dbd8313ed055', 'Male', 'victor.gif', 'Vasplus Blog', '', 'Malaysia', 'yes', '05-05-2013', '05-05-2013'),
(3, 'Greg Joshua', 'greg', 'vasplusblog#gmail.com', '81dc9bdb52d04dc20036dbd8313ed055', 'Male', 'c.jpg', 'Vasplus Programming Blog', '', 'United States of America', 'yes', '05-05-2013', '05-05-2013'),
(4, 'Emy Nero', 'pretty', 'vasplusblog#gmail.com', '81dc9bdb52d04dc20036dbd8313ed055', 'Female', 'd.jpg', 'Vasplus Programming Blog', '', 'Italy', 'yes', '05-05-2013', '05-05-2013'),
(5, 'Victor Barack', 'barack', 'vasplusblog#gmail.com', '81dc9bdb52d04dc20036dbd8313ed055', 'Male', 'b.jpg', '', '', 'United States of America', 'yes', '05-05-2013', '05-05-2013'),
(6, 'Chin Shi Hong', 'chin', 'vasplusblog#gmail.com', '81dc9bdb52d04dc20036dbd8313ed055', 'Male', 'a.jpg', '', '', 'Malaysia', 'yes', '05-05-2013', '05-05-2013'),
(7, 'Sydney Odell', 'ney', 'vasplusblog#gmail.com', '81dc9bdb52d04dc20036dbd8313ed055', 'Female', 'e.jpg', '', '', 'China', 'yes', '05-05-2013', '05-05-2013'),
(8, 'Engineer Bob', 'bobby', 'vasplusblog#gmail.com', '81dc9bdb52d04dc20036dbd8313ed055', 'Male', 'bobby.jpg', '', '', 'United States of America', 'yes', '05-05-2013', '05-05-2013');
CREATE TABLE IF NOT EXISTS `vpb_pms` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`touser` varchar(40) NOT NULL,
`fromuser` varchar(40) NOT NULL,
`subject` text NOT NULL,
`message` text NOT NULL,
`read` enum('0','1') NOT NULL DEFAULT '0',
`deleted` enum('0','1') NOT NULL DEFAULT '0',
`datesent` varchar(200) NOT NULL,
`outdel` enum('0','1') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `vpb_pms_attachments_main` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`uid` varchar(200) NOT NULL,
`from` varchar(200) NOT NULL,
`to` varchar(200) NOT NULL,
`file` varchar(200) NOT NULL,
`date` varchar(200) NOT NULL,
`delete` varchar(200) NOT NULL,
`outdelete` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `vpb_pms_attachments_temporal` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`uid` varchar(200) NOT NULL,
`from` varchar(200) NOT NULL,
`to` varchar(200) NOT NULL,
`file` varchar(200) NOT NULL,
`date` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Connect to the MySQL Client, and when you have authenticated yourself, and created the database (create database [database name];) then just execute the script with the command:
\. tables.sql
If your database was not created, create it first like this:
mysqladmin -uroot -p myRootPassword create myDatabaseName
If root has no password setup, forget the -p myRootPassword
Then run the following command from your the command line, being in your public_html folder:
mysql -u root -p myRootPassword mydatabaseName < tables.sql
Replace myRootPassword by your mysql root password and mydatabaseName by your database name.
If root has no password setup run it like this:
mysql -u root -p myRootPassword mydatabaseName < tables.sql
The geeky approach:
Step 1. Create your database:
mysql -h yourHost -u yourUser -pYourPassword -e"create database dbName";
(if you are working on localhost, you can omit the -h yourHost piece.
Step 2. Load your file on the newly created database:
mysql -h yourHost -u yourUser -pYourPassword dbName < tables.sql

Find all missing mapping table entries

I need to be able to determine all of the people that were missing from attendance in a series of meetings.
I have a solution to figure this problem out with JS on the client's computer but I think it could be done more efficiently on the server.
Table A (people) -> Table B (attendance) <- Table C(meeting)
The attendance is a mapping table of items in table A and C.
See: http://sqlfiddle.com/#!8/6db81 for the exact schema
What I want is to determine all of the meetings that people have missed. That is there is no entry for that person for that meeting in the attendance table B.
Desired output should include a minimum of the lid (user id) and mid (meeting ID).
lid, firstname, lastname, mid, meeting_title, start.
The solution in JS would be to send the results of a cross of A and C, and the results of B to the client. Then remove all of the items in B from the cross of A and C.
CREATE TABLE IF NOT EXISTS `attendance` (
`mid` bigint(20) NOT NULL,
`sid` bigint(20) DEFAULT NULL,
`entered` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`lid` varchar(64) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`mid`,`lid`),
KEY `entered` (`entered`)
);
INSERT INTO `attendance` (`mid`, `sid`, `entered`, `lid`) VALUES
(5, NULL, '2013-12-25 21:44:27', '100'),
(5, NULL, '2013-12-25 21:44:19', '200'),
(5, NULL, '2013-12-25 21:44:21', '300'),
(9, NULL, '2013-12-26 14:49:49', '200'),
(9, NULL, '2013-12-26 07:10:34', '300');
CREATE TABLE IF NOT EXISTS `meetings` (
`mid` bigint(11) NOT NULL AUTO_INCREMENT,
`title` varchar(32) CHARACTER SET utf8 NOT NULL,
`start` datetime NOT NULL COMMENT 'registration start time',
`stop` datetime NOT NULL COMMENT 'registration stop time',
PRIMARY KEY (`mid`),
UNIQUE KEY `title` (`title`)
);
INSERT INTO `meetings` (`mid`, `title`, `start`, `stop`) VALUES
(5, 'Meeting 1', '2013-12-25 01:12:00', '2013-12-25 23:12:00'),
(9, 'Meeting 2', '2013-12-26 01:00:00', '2013-12-26 23:00:00');
CREATE TABLE IF NOT EXISTS `people` (
`sid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`lid` varchar(64) NOT NULL,
`firstname` varchar(64) NOT NULL,
`lastname` varchar(64) NOT NULL,
`title` varchar(5) DEFAULT NULL,
`address` varchar(128) DEFAULT NULL,
`city` varchar(64) DEFAULT NULL,
`state` varchar(2) DEFAULT NULL,
`zip` varchar(9) DEFAULT NULL,
`phone` varchar(12) DEFAULT NULL,
`cell` varchar(12) DEFAULT NULL,
`email` varchar(64) DEFAULT NULL,
PRIMARY KEY (`sid`),
UNIQUE KEY `sid` (`sid`),
UNIQUE KEY `lid` (`lid`)
);
INSERT INTO `people` (`sid`, `lid`, `firstname`, `lastname`, `title`, `address`, `city`, `state`, `zip`, `phone`, `cell`, `email`) VALUES
(1, '100', 'Fred', 'Jones', 'Mr.', 'Somewhere', 'City', 'AK', '12345', '123-123-1234', '123-123-1234', 'email#email.com'),
(2, '200', 'Wilma', 'Jones', 'Mrs.', '', 'City', '', '12346', '', NULL, '');
You have to join people and meetings table to get all possible combinations of meeting id and userid and then filter out only those, which are not present in attendance table.
SELECT a.lid,
b.mid
FROM people a
CROSS JOIN meetings b
WHERE NOT EXISTS (SELECT 1
FROM attendance c
WHERE c.mid = b.mid
AND c.lid = a.lid);
Fiddle

database query to find trains between two stations on specific date like irctc.co.in

I have following database
Table structure for table trains
CREATE TABLE IF NOT EXISTS `trains` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`train_no` varchar(5) COLLATE latin1_general_ci DEFAULT NULL,
`train_name` varchar(50) COLLATE latin1_general_ci NOT NULL,
`runsfrom` varchar(50) COLLATE latin1_general_ci NOT NULL,
`SUN` varchar(3) COLLATE latin1_general_ci NOT NULL,
`MON` varchar(3) COLLATE latin1_general_ci NOT NULL,
`TUE` varchar(3) COLLATE latin1_general_ci NOT NULL,
`WED` varchar(3) COLLATE latin1_general_ci NOT NULL,
`THU` varchar(3) COLLATE latin1_general_ci NOT NULL,
`FRI` varchar(3) COLLATE latin1_general_ci NOT NULL,
`SAT` varchar(3) COLLATE latin1_general_ci NOT NULL,
`DOE` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1912 ;
having data like this:
INSERT INTO `trains` VALUES (269, '12307', 'HWH JU EXPRESS', 'HOWRAH JN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN', '2013-03-24');
INSERT INTO `trains` VALUES (270, '12308', 'JU HWH SUPFAST', 'JODHPUR JN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN', '2013-03-24');
INSERT INTO `trains` VALUES (381, '12461', 'MANDOR EXPRESS', 'DELHI', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN', '2013-03-24');
INSERT INTO `trains` VALUES (382, '12462', 'MANDOR EXPRESS', 'JODHPUR JN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN', '2013-03-24');
Table structure for table train_number
CREATE TABLE IF NOT EXISTS `train_number` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`train_no` varchar(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1912 ;
having data like this:
INSERT INTO `train_number` VALUES (269, '12307');
INSERT INTO `train_number` VALUES (270, '12308');
INSERT INTO `train_number` VALUES (381, '12461');
Table structure for table train_schedule
CREATE TABLE IF NOT EXISTS `train_schedule` (
`train_no` varchar(5) NOT NULL,
`stn_code` varchar(20) NOT NULL,
`stn_name` varchar(50) NOT NULL,
`route_no` varchar(2) NOT NULL,
`arr_time` varchar(5) NOT NULL,
`dep_time` varchar(5) NOT NULL,
`halt_time` varchar(5) NOT NULL,
`distance` varchar(4) NOT NULL,
`day` varchar(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
having data like this:
INSERT INTO `train_schedule` VALUES ('12307', 'HWH ', 'HOWRAH JN ', '1', 'Sourc', '23:30', '', '0', '1');
INSERT INTO `train_schedule` VALUES ('12307', 'BWN ', 'BARDDHAMAN JN ', '1', '00:35', '00:37', '2:00', '95', '2');
INSERT INTO `train_schedule` VALUES ('12307', 'ASN ', 'ASANSOL JN ', '1', '01:52', '01:56', '4:00', '200', '2');
INSERT INTO `train_schedule` VALUES ('12307', 'DHN ', 'DHANBAD JN ', '1', '03:05', '03:15', '10:00', '259', '2');
Now I want to find to find the trains between two stations on specific date. So I tried with this query
SELECT distinct d1.train_no
FROM train_schedule d1
INNER JOIN train_schedule d2 ON d2.train_no=d1.train_no
WHERE d1.stn_code = 'JU' and d2.stn_code = 'JP'
But it's showing both data from JU to JP and from JP to JU also so it makes the result double.
I want to make this query correct only for one direction on a specific date as days when it runs is also given in database
If i understand your question correctly, to answer the part to return only one direction, please try the query below:
SELECT d1.*
FROM train_schedule d1
INNER JOIN train_schedule d2 ON d2.train_no=d1.train_no
WHERE d1.stn_code = 'JU' and d2.stn_code = 'JP'
AND d1.distance < d2.distance
JU (departure) will always have distance less than JP (arrival).
Instead of sun...sat you should use 1..7 and make the value boolean or tinyint
SELECT distinct d1.train_no
FROM train_schedule d1 WHERE DAYOFWEEK(#yyyy-dd-mm#) = 1
INNER JOIN train_schedule d2 ON d2.train_no=d1.train_no
WHERE d1.stn_code = 'JU' and d2.stn_code = 'JP'
This should work