selecting multiple rows issue in mysql - mysql

I am beginner in sql.
I have two tables users and installments
CREATE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) NOT NULL,
`password` varchar(10) NOT NULL,
`father_name` varchar(20) NOT NULL,
`phone` varchar(20) NOT NULL,
`cnic` varchar(20) NOT NULL,
`email` varchar(100) NOT NULL,
`address` varchar(100) NOT NULL,
`introducer` varchar(100) NOT NULL,
`date` date DEFAULT NULL,
`reg_number` varchar(100) DEFAULT NULL,
`installment` int(100) NOT NULL,
`user_level` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `cnic` (`cnic`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `users` (`id`, `user_name`, `password`, `father_name`, `phone`, `cnic`, `email`, `address`, `introducer`, `date`, `reg_number`, `installment`, `user_level`) VALUES
(2, 'qaser', 'Qaser1', 'zamarrud', '0312546879', '37406-3140185-1', 'tariq_kareem#yahoo.com', 'street # 6', 'rizwan', '2014-08-20', 'E-002', 3000, 0);
and
CREATE `installments` (
`installment_id` int(11) NOT NULL AUTO_INCREMENT,
`month` date DEFAULT NULL,
`prv_arrear` int(100) NOT NULL,
`amount` int(100) NOT NULL,
`total` int(100) NOT NULL,
`receive` int(100) NOT NULL,
`arrear` int(100) NOT NULL,
`fk_users_id` int(11) NOT NULL,
PRIMARY KEY (`installment_id`),
KEY `fk_users_id` (`fk_users_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
INSERT INTO `installments` (`installment_id`, `month`, `prv_arrear`, `amount`, `total`, `receive`, `arrear`) VALUES
(2, '2014-08-20', 2000, 2500, 4500, 3000, 1500);
when I run the following query I get the first table's record correctly but the second table's record showing NULL values
SELECT * FROM users
LEFT JOIN installments
ON users.id=installments.installment_id
WHERE users.cnic='37406-3140185-1';
Is there anything missing in the above query or is there another way to get the record from both tables simultaneously
id user_name password father_name phone cnic email address introducer date reg_number installment user_level installment_id month prv_arrear amount total receive arrear fk_users_id
2 qaser Qaser1 zamarrud 0312546879 37406-3140185-1 tariq_kareem#yahoo.com street # 6 rizwan 2014-08-20 s-001 3000 0 NULL NULL NULL NULL NULL NULL NULL NULL
I am also using the following query to inserting the record for getting primary key value and insert into foreign key
INSERT INTO `installments`(`id`, `month`, `prv_arrear`, `amount`, `total`, `receive`, `arrear`, fk_users_id)
SELECT NULL,now(),1000,2500,3500,3000,500, id
FROM users
WHERE cnic = '37406-3140190-1'
please help me thanks in advance and sorry if there is something wrong in my question because I am new in sql.

I suspect the right join condition is on fk_users_id. So this might do what you want:
SELECT *
FROM users u LEFT JOIN
installments i
ON u.id = i.fk_users_id
WHERE u.cnic = '37406-3140185-1';

Related

SQL query not returning correct result using three table together?

I have 3 tables in which tbl_user_signup_info, tbl_main_lead_info and tbl_campaign_info, I need a result in which it display info such that each row display the lead id and campaign id added by corresponding registered users of the tbl_user_signup_info and display should be like User_Id, Lead_Id, Campaign_ID.
Actually i want Total number of leads added by particular user with there Lead Id and Total number of campaign added by that user with there Campaign_Id using those 3 tables.
But i am lacking to form SQL query.
My Result are as below which are wrong:
Table structure
--
-- Table structure for table `tbl_campaign_info`
--
DROP TABLE IF EXISTS `tbl_campaign_info`;
CREATE TABLE IF NOT EXISTS `tbl_campaign_info` (
`Campaign_Id` int(100) NOT NULL AUTO_INCREMENT,
`CampaignName` varchar(200) NOT NULL,
`CampaignStatus` varchar(200) NOT NULL,
`CampaignDescription` varchar(200) DEFAULT NULL,
`CampaignOwnerNotes` varchar(200) DEFAULT NULL,
`CampaignAdminNotes` varchar(200) DEFAULT NULL,
`CampaignStartDate` date NOT NULL,
`CampaignEndDate` date NOT NULL,
`CampaignLead_Id` int(100) NOT NULL,
`CampaignAddedBy` int(100) NOT NULL,
`CampaignAddedOn` date DEFAULT NULL,
UNIQUE KEY `Campaign_Id` (`Campaign_Id`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=latin1;
--
-- Table structure for table `tbl_main_lead_info`
--
DROP TABLE IF EXISTS `tbl_main_lead_info`;
CREATE TABLE IF NOT EXISTS `tbl_main_lead_info` (
`Lead_Id` int(100) NOT NULL AUTO_INCREMENT,
`FirstName` varchar(100) DEFAULT NULL,
`LastName` varchar(100) DEFAULT NULL,
`Company` varchar(100) DEFAULT 'NA',
`Website` varchar(100) DEFAULT 'NA',
`Designation` varchar(100) DEFAULT 'NA',
`Linkedin` varchar(100) DEFAULT 'NA',
`Email` varchar(100) DEFAULT NULL,
`Phone` varchar(100) DEFAULT NULL,
`State` varchar(100) DEFAULT NULL,
`Country` varchar(100) DEFAULT NULL,
`TechArea` varchar(100) DEFAULT NULL,
`FirmType` varchar(100) DEFAULT NULL,
`FirmSize` varchar(100) DEFAULT NULL,
`LastContactDate` date DEFAULT NULL,
`NextContactDate` date DEFAULT NULL,
`LeadDescription` varchar(200) DEFAULT NULL,
`OwnerNotes` varchar(200) DEFAULT NULL,
`SetReminder` date DEFAULT NULL,
`AdminNotes` varchar(200) DEFAULT NULL,
`LeadStatus` varchar(100) DEFAULT NULL,
`LeadAddedBy` int(100) NOT NULL,
`LeadAddedOn` datetime DEFAULT NULL,
PRIMARY KEY (`Lead_Id`),
UNIQUE KEY `FirstName` (`FirstName`,`LastName`,`Company`,`Website`,`Designation`,`Linkedin`,`Email`,`Phone`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_main_lead_info`
--
INSERT INTO `tbl_main_lead_info` (`Lead_Id`, `FirstName`, `LastName`, `Company`, `Website`, `Designation`, `Linkedin`, `Email`, `Phone`, `State`, `Country`, `TechArea`, `FirmType`, `FirmSize`, `LastContactDate`, `NextContactDate`, `LeadDescription`, `OwnerNotes`, `SetReminder`, `AdminNotes`, `LeadStatus`, `LeadAddedBy`, `LeadAddedOn`) VALUES
(15, 'John', 'Doe', 'test', 'test', 'test', 'test', 'test', 'test', 'Texas', 'USA', 'test', 'Corporate', '11-50', '2020-01-09', '2020-01-10', 'Testing Description of Lead information', NULL, '2020-01-11', 'This need to be confidential by admin', 'Active', 18, '2020-01-09 16:07:17');
--
-- Dumping data for table `tbl_campaign_info`
--
INSERT INTO `tbl_campaign_info` (`Campaign_Id`, `CampaignName`, `CampaignStatus`, `CampaignDescription`, `CampaignOwnerNotes`, `CampaignAdminNotes`, `CampaignStartDate`, `CampaignEndDate`, `CampaignLead_Id`, `CampaignAddedBy`, `CampaignAddedOn`) VALUES
(16, 'Test', 'Active', 'Test', NULL, 'This is admin notes and need to be kept confidential', '2020-01-09', '2020-01-10', 15, 18, '2020-01-09'),
(17, 'Test', 'Active', 'Test ', NULL, 'NA', '2020-01-10', '2020-01-10', 15, 18, '2020-01-09');
--
-- Table structure for table `tbl_user_signup_info`
--
DROP TABLE IF EXISTS `tbl_user_signup_info`;
CREATE TABLE IF NOT EXISTS `tbl_user_signup_info` (
`User_Id` int(50) NOT NULL AUTO_INCREMENT,
`UserEmail` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`UserName` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`UserPassword` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`Admin` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`User_Id`) USING BTREE,
UNIQUE KEY `Email` (`UserEmail`),
UNIQUE KEY `UserName` (`UserName`),
UNIQUE KEY `UserEmail` (`UserEmail`,`UserName`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `tbl_user_signup_info`
--
INSERT INTO `tbl_user_signup_info` (`User_Id`, `UserEmail`, `UserName`, `UserPassword`, `Admin`) VALUES
(18, 'test#gmail.com', 'test', 'test', 1),
(22, 'test1#gmail.com', 'test1', 'test1', 0),
(23, 'test2#gmail.com', 'test2', 'test2', 0);
COMMIT;
and My SQl Query is as below:
SELECT User_Id, Campaign_Id, Lead_Id
FROM tbl_campaign_info AS C,
tbl_main_lead_info AS M,
tbl_user_signup_info AS U
WHERE C.CampaignAddedBy IN ( SELECT User_Id
FROM tbl_user_signup_info AS U,
tbl_campaign_info AS C
WHERE U.User_Id = C.CampaignAddedBy)
AND M.LeadAddedBy IN (SELECT User_Id
FROM tbl_user_signup_info AS U,
tbl_main_lead_info AS M
WHERE U.User_Id = M.LeadAddedBy )
If I understand correctly, you want users campaign counts and lead counts per user. So, select campaign counts, select lead counts, join them.
You could use a full outer join of the two results for this (thus getting only those users that have at least one campain or lead), but MySQL doesn't support it. I take it that tbl_user_signup_info contains one row per user, though, so you can use this as a base table. The following query gives you a result for every user in that table.
select
u.user_id,
coalesce(c.total, 0) as campaign_count,
coalesce(l.total, 0) as lead_count
from tbl_user_signup_info u
left join
(
select campaignaddedby, count(*) as total
from tbl_campaign_info
group by campaignaddedby
) c on c.campaignaddedby = u.user_id
left join
(
select leadaddedby, count(*) as total
from tbl_main_lead_info
group by leadaddedby
) l on l.leadaddedby = u.user_id
order by u.user_id;
It seems like you can only use JOIN.
SELECT U.User_Id, Campaign_Id, Lead_Id
FROM tbl_user_signup_info AS U
JOIN tbl_campaign_info AS C ON U.User_Id = C.CampaignAddedBy
JOIN tbl_main_lead_info AS M ON U.User_Id = M.LeadAddedBy
Actually i want Total number of leads added by particular user with
there Lead Id and Total number of campaign added by that user with
there Campaign_Id using those 3 tables.
Try this:
SELECT
X.USER_ID,
X.LeadCount,
IF(Y.LEAD_ID IS NULL, 0, Y.LEAD_ID) LEAD_ID,
IF(Y.CampaignCount IS NULL, 0, Y.CampaignCount) CampaignCount
FROM (
SELECT
U.User_ID, COUNT(DISTINCT LEAD_ID) LeadCount
FROM
tbl_user_signup_info U
LEFT JOIN
tbl_main_lead_info M
ON (U.User_Id = M.LeadAddedBy)
GROUP BY
U.USER_ID
) X
LEFT JOIN
(
SELECT
M.LeadAddedBy, M.LEAD_ID, COUNT(DISTINCT Campaign_Id) CampaignCount
FROM
tbl_campaign_info C
LEFT JOIN
tbl_main_lead_info M
ON (C.CampaignAddedBy = M.LeadAddedBy)
GROUP BY
M.LeadAddedBy, M.LEAD_ID
) Y
ON (
X.USER_ID = Y.LeadAddedBy
)
SQL Fiddle link: http://sqlfiddle.com/#!9/4e138/40

Join two tables where one table name is inside the other table

I am registering various properties in the property table. Depending on the type of property, three new tables namely apartment, villa, land is used to store specific data. So what I have is the a master table which holds property URL, Property type, Ref table name (any of the three sub table name - apartment, villa, land) and the ref id which is the primary autoincrement key of the sub tables.
I tried the three seperated select query and Union of the result. The drawback is that the results will be mostly from the first table name uses among the three.
function getMyProperty() {
$tables = $this->getPropertyTables();
$result = array();
foreach ($tables as $key => $table) {
$this->db->select('a.main_heading, a.sub_heading, a.location, a.about_property, a.property_price, a.available_from, p.property_url');
$this->db->from('property p');
$this->db->join($table . ' a', 'p.ref_id = a.id');
$this->db->where('p.posted_by', $this->session->user_id);
$this->db->where('p.ref_table', $this->db->dbprefix($table));
$query = $this->db->get();
$res = $query->result();
$result = array_merge($result, $res);
}
return $result;
}
DB SCHEMA
CREATE TABLE `apartment` (
`id` int(11) NOT NULL,
`main_heading` varchar(256) NOT NULL,
`sub_heading` text NOT NULL,
`build_up_area` int(11) NOT NULL,
`carpet_area` int(11) NOT NULL,
`no_of_bedrooms` int(11) NOT NULL,
`bathrooms` int(11) NOT NULL,
`available_from` date NOT NULL,
`furnishing` varchar(256) NOT NULL,
`facing` varchar(100) NOT NULL,
`flooring` varchar(256) NOT NULL,
`parking` varchar(256) NOT NULL,
`width_of_facing_road` varchar(100) NOT NULL,
`property_age` int(11) NOT NULL,
`property_price` decimal(16,2) NOT NULL DEFAULT '0.00',
`address` text NOT NULL,
`about_property` text NOT NULL,
`location` varchar(256) NOT NULL,
`amenities` text NOT NULL,
`owner_name` varchar(256) NOT NULL,
`owner_email` varchar(256) NOT NULL,
`owner_phone` varchar(100) NOT NULL,
`active` enum('Y','N') NOT NULL DEFAULT 'Y'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
INSERT INTO `apartment` (`id`, `main_heading`, `sub_heading`, `build_up_area`, `carpet_area`, `no_of_bedrooms`, `bathrooms`, `available_from`, `furnishing`, `facing`, `flooring`, `parking`, `width_of_facing_road`, `property_age`, `property_price`, `address`, `about_property`, `location`, `amenities`, `owner_name`, `owner_email`, `owner_phone`, `active`) VALUES
(2, 'My Appartment', 'Place', 255, 400, 4, 4, '2019-08-08', 'semi', 'north', 'vitrified', '2', '15', 15, '15.00', 'ghkgkgk', 'jkhjkhjk', 'Kochi', '', 'Agent', 'abc#edg.com', '9876543210', 'Y'),
(3, 'My Appartment 2', 'Test', 255, 400, 4, 4, '2019-08-08', 'semi', 'north', 'vitrified', '2', '15', 15, '15.00', 'ghkgkgk', 'jkhjkhjk', 'Kochi', '', 'Agent', 'abc#edg.com', '9876543210', 'Y');
CREATE TABLE `land` (
`id` int(11) NOT NULL,
`main_heading` varchar(256) NOT NULL,
`sub_heading` text NOT NULL,
`plot_area` int(11) NOT NULL,
`gated_colony` int(11) NOT NULL,
`open_sides` int(11) NOT NULL,
`available_from` date NOT NULL,
`dimensions` varchar(256) NOT NULL,
`facing` varchar(100) NOT NULL,
`boundary_wall` varchar(256) NOT NULL,
`parking` varchar(256) NOT NULL,
`width_of_facing_road` varchar(100) NOT NULL,
`property_age` int(11) NOT NULL,
`property_price` decimal(16,2) NOT NULL DEFAULT '0.00',
`address` text NOT NULL,
`about_property` text NOT NULL,
`location` varchar(256) NOT NULL,
`owner_name` varchar(256) NOT NULL,
`owner_email` varchar(256) NOT NULL,
`owner_phone` varchar(100) NOT NULL,
`active` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
CREATE TABLE `property` (
`property_id` int(11) NOT NULL,
`posted_by` int(11) NOT NULL,
`post_type` enum('RENT','SELL','LEASE') NOT NULL,
`property_type` enum('VILLA','APARTMENT','LAND') NOT NULL,
`property_url` varchar(50) NOT NULL,
`ref_table` varchar(50) NOT NULL DEFAULT '',
`ref_id` int(11) NOT NULL DEFAULT '0',
`posted_on` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
INSERT INTO `property` (`property_id`, `posted_by`, `post_type`, `property_type`, `property_url`, `ref_table`, `ref_id`, `posted_on`) VALUES
(4, 1, 'SELL', 'VILLA', 'lyohlp', 'villa', 2, '2019-08-05'),
(5, 1, 'SELL', 'APARTMENT', 'cvbdit', 'apartment', 2, '2019-08-05'),
(6, 2, 'SELL', 'APARTMENT', 'qwerty', 'apartment', 3, '2019-08-05'),
(7, 3, 'RENT', 'VILLA', 'asdfgh', 'villa', 3, '2019-08-05');
CREATE TABLE `villa` (
`id` int(11) NOT NULL,
`main_heading` varchar(256) NOT NULL,
`sub_heading` text NOT NULL,
`build_up_area` int(11) NOT NULL,
`carpet_area` int(11) NOT NULL,
`no_of_bedrooms` int(11) NOT NULL,
`bathrooms` int(11) NOT NULL,
`available_from` date NOT NULL,
`furnishing` varchar(256) NOT NULL,
`facing` varchar(100) NOT NULL,
`flooring` varchar(256) NOT NULL,
`total_area` varchar(256) NOT NULL,
`width_of_facing_road` varchar(100) NOT NULL,
`property_age` int(11) NOT NULL,
`property_price` decimal(16,2) NOT NULL DEFAULT '0.00',
`address` text NOT NULL,
`about_property` text NOT NULL,
`location` varchar(256) NOT NULL,
`amenities` text NOT NULL,
`owner_name` varchar(256) NOT NULL,
`owner_email` varchar(256) NOT NULL,
`owner_phone` varchar(100) NOT NULL,
`active` enum('Y','N') NOT NULL DEFAULT 'Y'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
INSERT INTO `villa` (`id`, `main_heading`, `sub_heading`, `build_up_area`, `carpet_area`, `no_of_bedrooms`, `bathrooms`, `available_from`, `furnishing`, `facing`, `flooring`, `total_area`, `width_of_facing_road`, `property_age`, `property_price`, `address`, `about_property`, `location`, `amenities`, `owner_name`, `owner_email`, `owner_phone`, `active`) VALUES
(2, 'My Villa', 'Kakkanad', 54, 5, 4, 4, '2019-08-06', 'semi', 'west', 'not-vitrified', '111', '10', 0, '12.00', 'fhgfgh', 'ghfghf', 'Kochi', 'car_parking,water_supply,garden,fitness_center,shower,fridge', 'dfdfdf', 'abc#edg.com', '9876543210', 'Y'),
(3, 'My Villa 2', 'Place', 54, 5, 4, 4, '2019-08-06', 'semi', 'west', 'not-vitrified', '111', '10', 0, '12.00', 'fhgfgh', 'ghfghf', 'Kochi', 'car_parking,water_supply,garden,fitness_center,shower,fridge', 'dfdfdf', 'abc#edg.com', '9876543210', 'Y');
ALTER TABLE `apartment`
ADD PRIMARY KEY (`id`);
ALTER TABLE `land`
ADD PRIMARY KEY (`id`);
ALTER TABLE `property`
ADD PRIMARY KEY (`property_id`),
ADD KEY `ref_id` (`ref_id`);
ALTER TABLE `villa`
ADD PRIMARY KEY (`id`);
ALTER TABLE `apartment`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
ALTER TABLE `land`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `property`
MODIFY `property_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
ALTER TABLE `villa`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
I expect result based on the decreasing of post date irrespective of the order of the table I provided.
As we know only one of the type can be mapped with the property.
So data will be generated from one table(which store details of that property type) only, other tables will produce null.
A great way to pick data from multiple columns if only one of them is not null, is using CONCAT_WS or COALESCE.
SELECT
P.property_id, P.property_url,
CONCAT_WS('', V.main_heading, A.main_heading, L.main_heading) AS main_heading,
CONCAT_WS('', V.sub_heading, A.sub_heading, L.sub_heading) AS sub_heading,
CONCAT_WS('', V.location, A.location, L.location) AS location,
CONCAT_WS('', V.about_property, A.about_property, L.about_property) AS about_property,
CONCAT_WS('', V.property_price, A.property_price, L.property_price) AS property_price,
CONCAT_WS('', V.available_from, A.available_from, L.available_from) AS available_from,
P.posted_on
FROM property P
LEFT JOIN villa V ON P.ref_table = 'villa' AND P.ref_id = V.id
LEFT JOIN apartment A ON P.ref_table = 'apartment' AND P.ref_id = A.id
LEFT JOIN land L ON P.ref_table = 'land' AND P.ref_id = L.id
ORDER BY P.posted_on DESC;
Using COALESCE at place of CONCAT_WS would be like:
COALESCE(V.main_heading, A.main_heading, L.main_heading) AS main_heading
Reference: MySQL Function: COALESCE, MySQL Function: CONCAT_WS
You can integrate the following query in CI instead of looping in php. It provides single set array.
SELECT
a.*,
b.id,
c.id,
d.id
FROM
`property` AS a
LEFT JOIN `apartment` AS b
ON a.`ref_id` = b.id
AND a.`ref_table` = 'apartment'
LEFT JOIN `land` AS c
ON a.`ref_id` = c.id
AND a.`ref_table` = 'land'
LEFT JOIN `villa` AS d
ON a.`ref_id` = d.id
AND a.`ref_table` = 'villa'
ORDER BY a.`posted_by` DESC ;
Here, joining tables respective of constant table name and other fields will return null.Those conditions can map in PHP code.
Note : add necessary columns in select what you needed.
add this condition too : $this->db->where('p.posted_by', $this->session->user_id); in query

Finding out if there is a daily insert into mysql table

I have this table which should be getting daily input regarding Vehicle mileage Readings.
CREATE TABLE `table_vehicle_info` (
`id` int(11) NOT NULL ,
`reg_no` varchar(50) NOT NULL,
`vehicle_type` int(11) NOT NULL,
`engine_no` varchar(50) NOT NULL DEFAULT "DDDD",
`chassis_no` varchar(50) ,
`model` int(11) DEFAULT NULL,
`picture` varchar(50) ,
`rent` double ,
`eng_power` int(11) DEFAULT NULL,
`color` varchar(12) DEFAULT NULL,
`rent_status` varchar(50) DEFAULT NULL,
`reg_city` varchar(50) DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`sub_type` varchar(50) DEFAULT NULL,
`purchase_date` date DEFAULT NULL,
`purchase_amount` double DEFAULT NULL,
`sum_insured` double DEFAULT NULL,
`token_tax_amount` double DEFAULT NULL,
`token_period_from` date DEFAULT NULL,
`reg_placed_at` varchar(50) DEFAULT NULL,
`funded_by` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=99 DEFAULT CHARSET=latin1;
CREATE TABLE `tbl_readings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`vehicle_id` int(11) NOT NULL,
`km_driven` int(11) NOT NULL,
`dt_of_reading` datetime NOT NULL,
`dt_of_entry` datetime NOT NULL,
`entry_user` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `vehicle_id` (`vehicle_id`),
CONSTRAINT `tbl_readings_ibfk_1` FOREIGN KEY (`vehicle_id`) REFERENCES `table_vehicle_info` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1;
INSERT INTO table_vehicle_info (id,reg_no,vehicle_type )
VALUES (1, "B-5484", 12 );
INSERT INTO tbl_readings VALUES (NULL,1,100,'2015-6-1',NOW(), 'user');
I want to generate a report showing which vehicle reading isn't entered daily.
You can try following query, it returns all vehicle_id from tbl_readings for which there is no next day entry.
SELECT vehicle_id
FROM `tbl_readings`
WHERE DATE(DATE_ADD(dt_of_entry,INTERVAL 1 DAY)) NOT IN
(SELECT DATE(dt_of_entry) FROM `tbl_readings`)
EDIT
Try this,
SELECT t1.vehicle_id
FROM `tbl_readings` t1
LEFT JOIN (SELECT vehicle_id,
DATE(DATE_ADD(dt_of_reading,INTERVAL -1 DAY)) as reading_date
FROM `tbl_readings`) t2
ON t1.vehicle_id = t2.vehicle_id AND t1.dt_of_reading = t2.reading_date
WHERE t2.vehicle_id IS NULL
GROUP BY t1.vehicle_id
HAVING COUNT(t1.vehicle_id) > 1;
check the fiddle

MySQL joining 2 tables in to one main table

I have 2 tables 'cat' and 'sub_cat' and these two tables should join or something with main table 'product'
I tried all joining methods and non of them gave me right result I want.
I'm sure there is a method. I don't know what to call.
Sample SQL
This is how the last query should be
forget about the normalization theories and every thing and I just want the last query to be like this or mysql method that I can use on this.
cat_id cannot be duplicate
s_id should also cannot be duplicate
like in third row there can be: cat_id but no s_id the s_id should be null
if there is no cat_id and no s_id both should be null like fourth row
p_id can be duplicate
can't use group by or distinct cause it doesn't give null values then as i know
only method i got closer is using left joining both cat and sub_cat to prod table but it gives me duplicate cat_id and s_id and can't use group by or distinct on this cause there should be null values.
here is the test data
CREATE TABLE IF NOT EXISTS `cat` (
`product_id` int(11) DEFAULT NULL,
`cat_id` int(11) DEFAULT NULL,
`cat_name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `cat` (`product_id`, `cat_id`, `cat_name`) VALUES
(1, 1, 'cat1'),
(2, 2, 'cat2'),
(3, 3, 'cat3'),
(1, 4, 'ca4');
CREATE TABLE IF NOT EXISTS `prod` (
`product_id` int(11) DEFAULT NULL,
`name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `prod` (`product_id`, `name`) VALUES
(1, 'prod1'),
(2, 'prod2'),
(3, 'pro3'),
(4, 'prod4');
CREATE TABLE IF NOT EXISTS `sub_cat` (
`product_id` int(11) DEFAULT NULL,
`sub_cat_id` int(11) DEFAULT NULL,
`sub_cat_name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `sub_cat` (`product_id`, `sub_cat_id`, `sub_cat_name`) VALUES
(1, 1, 'sub cat 1'),
(2, 2, 'sub cat 2'),
(1, 3, 'sub3');
I have done a similar thing in this one.prop_cat acts as you Category table,prop_subcat as your subcategory table and property as you product.
CREATE TABLE `prop_cat` (
`pcat_id` int(11) NOT NULL AUTO_INCREMENT,
`pcat_name` varchar(60) DEFAULT NULL,
PRIMARY KEY (`pcat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `prop_subcat` (
`psubcat_id` int(11) NOT NULL,
`pcat_id` int(11) NOT NULL,
`psubcat_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`psubcat_id`,`pcat_id`),
KEY `pspc_idx` (`pcat_id`),
CONSTRAINT `catsub` FOREIGN KEY (`pcat_id`) REFERENCES `prop_cat` (`pcat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `property` (
`prop_id` int(11) NOT NULL AUTO_INCREMENT,
`prop_name` varchar(25) DEFAULT NULL,
`price` double DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`image` varchar(60) DEFAULT NULL,
`area` double DEFAULT NULL,
`psubcat_id` int(11) DEFAULT NULL,
`description` text,
PRIMARY KEY (`prop_id`),
KEY `psub_idx` (`psubcat_id`),
CONSTRAINT `psub` FOREIGN KEY (`psubcat_id`) REFERENCES `prop_subcat` (`pcat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
SELECT
prop_cat.`pcat_id` AS prop_cat_pcat_id,
prop_cat.`pcat_name` AS prop_cat_pcat_name,
prop_subcat.`psubcat_id` AS prop_subcat_psubcat_id,
prop_subcat.`pcat_id` AS prop_subcat_pcat_id,
prop_subcat.`psubcat_name` AS prop_subcat_psubcat_name,
property.`prop_id` AS property_prop_id,
property.`prop_name` AS property_prop_name,
property.`price` AS property_price,
property.`location` AS property_location,
property.`image` AS property_image,
property.`area` AS property_area,
property.`psubcat_id` AS property_psubcat_id,
property.`description` AS property_description
FROM
`prop_cat` prop_cat INNER JOIN `prop_subcat` prop_subcat ON prop_cat.`pcat_id` = prop_subcat.`pcat_id`
INNER JOIN `property` property ON prop_subcat.`pcat_id` = property.`psubcat_id`

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