SQL Query to show documents for specific users when joined - mysql

I have created a document upload system, where an organisation will tell a user "you need to upload these X documents". Then the user gets an email, and can go to the profile page of that organisation and upload each of these documents in its corresponding upload form.
I have created 3 tables for this, vrm_document (this holds all the documents that are uploaded to the document system by organisations). vrm_document_user_link (this shows the documents linked from an organisation to a user). And vrm_document_user_upload (this holds the documents uploaded by the user to the organisation).
I cannot get my query right to show all the documents the user needs to upload together with the values whether it's uploaded already or not.
I have created a DBFiddle showing the query with the faulty data that is returning. In the example output of the DB Fiddle, the first row is returning a value for vrm_document_user_upload_id and document_path, while these are values for another user, but since the vrm_document_id matches, it shows these values here.
How do I solve this query?
This is the database structure I have created, together with the inserts:
CREATE TABLE vrm_document(
`vrm_document_id` INT(11) NOT NULL AUTO_INCREMENT,
`parent_vrm_document_id` INT(11) DEFAULT NULL,
`is_default_document` TINYINT(3) DEFAULT '0',
`country_id` INT(11) DEFAULT NULL COMMENT 'used only if document is a default document',
`user_id` INT(11) DEFAULT NULL COMMENT 'user id of who it is created for, null for default documents',
`user_auth_level` INT(11) DEFAULT NULL,
`title` VARCHAR(255) NOT NULL,
`version_name` VARCHAR(255) DEFAULT NULL,
`description` VARCHAR(255) DEFAULT NULL COMMENT 'empty for certain document types',
`vrm_document_type_id` INT(11) NOT NULL,
`document_preview` VARCHAR(255) NULL,
`document_preview_thumbnail` VARCHAR(255) NULL,
`document_path` VARCHAR(255) DEFAULT NULL,
`language_id` INT(11) DEFAULT NULL,
`timestamp_created_utc` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`timestamp_modified_utc` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`create_user_id` INT(11) DEFAULT NULL COMMENT 'the user id of who created the document',
`create_user_auth_level` INT(11) DEFAULT NULL,
`create_user_id_toggle` INT(11) DEFAULT NULL COMMENT 'user id of who was toggled to to create the document',
`create_user_auth_level_toggle` INT(11) DEFAULT NULL,
PRIMARY KEY (`vrm_document_id`)
) ENGINE = InnoDB;
CREATE TABLE vrm_document_user_upload(
`vrm_document_user_upload_id` INT(11) NOT NULL AUTO_INCREMENT,
`from_user_id` INT(11) NOT NULL,
`from_user_auth_level` INT(11) NOT NULL,
`to_user_id` INT(11) NOT NULL,
`to_user_auth_level` INT(11) NOT NULL,
`vrm_document_id` INT(11) NOT NULL,
`document_path` VARCHAR(255) NOT NULL,
`vrm_document_upload_status_id` INT(11) NOT NULL DEFAULT 0,
`reject_reason` VARCHAR(255) DEFAULT NULL,
`timestamp_uploaded_utc` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`create_user_id` INT(11) DEFAULT NULL COMMENT 'the user id of who uploaded the document',
`create_user_auth_level` INT(11) DEFAULT NULL,
`create_user_id_toggle` INT(11) DEFAULT NULL COMMENT 'user id of who was toggled to to upload the document',
`create_user_auth_level_toggle` INT(11) DEFAULT NULL,
PRIMARY KEY (`vrm_document_user_upload_id`)
) ENGINE = InnoDB;
CREATE TABLE vrm_document_user_link(
`from_user_id` INT(11) NOT NULL COMMENT 'the user id who attached the document to another user',
`to_user_id` INT(11) NOT NULL COMMENT 'the user id who the document is attached to',
`vrm_document_id` INT(11) NOT NULL,
FOREIGN KEY (`vrm_document_id`) REFERENCES `vrm_document` (`vrm_document_id`)
) ENGINE = InnoDB;
INSERT INTO `vrm_document` (`vrm_document_id`, `parent_vrm_document_id`, `is_default_document`, `country_id`, `user_id`, `user_auth_level`, `title`, `version_name`, `description`, `vrm_document_type_id`, `document_preview`, `document_preview_thumbnail`, `document_path`, `language_id`, `timestamp_created_utc`, `timestamp_modified_utc`, `create_user_id`, `create_user_auth_level`, `create_user_id_toggle`, `create_user_auth_level_toggle`) VALUES (1, NULL, 1, 19, NULL, NULL, 'Vrijwilligerscontract', 'Vrijwilligerscontract - Give a Day', 'Standaard vrijwilligerscontract aangeboden door Give a Day.', 2, NULL, NULL, '/vrm/documents/default_documents/180130_Uitnodiging_Aventi-in-beweging_v2.pdf', 14, '2020-03-27 14:53:19', '2020-03-27 14:53:19', NULL, NULL, NULL, NULL);
INSERT INTO `vrm_document` (`vrm_document_id`, `parent_vrm_document_id`, `is_default_document`, `country_id`, `user_id`, `user_auth_level`, `title`, `version_name`, `description`, `vrm_document_type_id`, `document_preview`, `document_preview_thumbnail`, `document_path`, `language_id`, `timestamp_created_utc`, `timestamp_modified_utc`, `create_user_id`, `create_user_auth_level`, `create_user_id_toggle`, `create_user_auth_level_toggle`) VALUES (9, NULL, 0, NULL, 2, 5, 'Nieuw doc als test', 'v1', 'Dit is een test', 2, NULL, NULL, 'vrm/documents/uploaded_documents/2020/03/template for evaluation of KBC Minimal Data Security requirements v2.0-DRAFT1-27032020163601.docx', 14, '2020-03-27 17:36:01', '2020-03-27 17:36:01', 1, 1, 2, 5);
INSERT INTO `vrm_document` (`vrm_document_id`, `parent_vrm_document_id`, `is_default_document`, `country_id`, `user_id`, `user_auth_level`, `title`, `version_name`, `description`, `vrm_document_type_id`, `document_preview`, `document_preview_thumbnail`, `document_path`, `language_id`, `timestamp_created_utc`, `timestamp_modified_utc`, `create_user_id`, `create_user_auth_level`, `create_user_id_toggle`, `create_user_auth_level_toggle`) VALUES (10, NULL, 0, NULL, 2, 5, 'Attest goed gedrag en zeden', '', 'Het attest van gedrag en goede zeden moet opgevraagd worden en terug opgeladen worden voor elke vrijwilliger die start bij ons. ', 3, NULL, NULL, NULL, 14, '2020-03-27 18:40:42', '2020-03-27 18:40:42', 1, 1, 2, 5);
INSERT INTO `vrm_document` (`vrm_document_id`, `parent_vrm_document_id`, `is_default_document`, `country_id`, `user_id`, `user_auth_level`, `title`, `version_name`, `description`, `vrm_document_type_id`, `document_preview`, `document_preview_thumbnail`, `document_path`, `language_id`, `timestamp_created_utc`, `timestamp_modified_utc`, `create_user_id`, `create_user_auth_level`, `create_user_id_toggle`, `create_user_auth_level_toggle`) VALUES (12, NULL, 0, NULL, 2, 5, 'test type 3', '', 'test voor type 3', 3, NULL, NULL, NULL, 14, '2020-03-31 07:19:14', '2020-03-31 07:19:14', 1, 1, 2, 5);
INSERT INTO `vrm_document` (`vrm_document_id`, `parent_vrm_document_id`, `is_default_document`, `country_id`, `user_id`, `user_auth_level`, `title`, `version_name`, `description`, `vrm_document_type_id`, `document_preview`, `document_preview_thumbnail`, `document_path`, `language_id`, `timestamp_created_utc`, `timestamp_modified_utc`, `create_user_id`, `create_user_auth_level`, `create_user_id_toggle`, `create_user_auth_level_toggle`) VALUES (64, NULL, 0, NULL, 2, 5, 'ooooooooo111', '', 'aezfs<wvcxcvw', 3, NULL, NULL, NULL, 14, '2020-04-03 12:21:06', '2020-04-03 12:21:06', 1, 1, 2, 5);
INSERT INTO `vrm_document_user_link` (`from_user_id`, `to_user_id`, `vrm_document_id`) VALUES (2, 24, 1);
INSERT INTO `vrm_document_user_link` (`from_user_id`, `to_user_id`, `vrm_document_id`) VALUES (2, 24, 9);
INSERT INTO `vrm_document_user_link` (`from_user_id`, `to_user_id`, `vrm_document_id`) VALUES (2, 24, 10);
INSERT INTO `vrm_document_user_link` (`from_user_id`, `to_user_id`, `vrm_document_id`) VALUES (2, 24, 12);
INSERT INTO `vrm_document_user_link` (`from_user_id`, `to_user_id`, `vrm_document_id`) VALUES (2, 24, 64);
INSERT INTO `vrm_document_user_upload` (`vrm_document_user_upload_id`, `from_user_id`, `from_user_auth_level`, `to_user_id`, `to_user_auth_level`, `vrm_document_id`, `document_path`, `vrm_document_upload_status_id`, `reject_reason`, `timestamp_uploaded_utc`, `create_user_id`, `create_user_auth_level`, `create_user_id_toggle`, `create_user_auth_level_toggle`) VALUES (5, 1, 1, 2, 5, 1, 'vrm/documents/user_uploaded_documents/2020/04/helpende-handen-werf-44-01042020125653-07042020162326.docx', 1, NULL, '2020-04-07 16:23:26', 1, 1, NULL, NULL);
And this is the Query I am trying to give me correct results:
SELECT vdul.*, vd.title, vd.description, vduu.vrm_document_user_upload_id, vduu.document_path
FROM vrm_document_user_link AS vdul
LEFT JOIN vrm_document_user_upload AS vduu ON vdul.vrm_document_id = vduu.vrm_document_id
LEFT JOIN vrm_document AS vd ON vdul.vrm_document_id = vd.vrm_document_id
WHERE vdul.from_user_id = 2
AND vdul.to_user_id = 24
AND vd.vrm_document_type_id != 1
Update second query after response from Balmar:
SELECT vdul.*, vd.title, vd.description, vduu.vrm_document_user_upload_id, vduu.document_path
FROM vrm_document_user_link AS vdul
LEFT JOIN vrm_document_user_upload AS vduu ON ((vdul.vrm_document_id = vduu.vrm_document_id) AND (vdul.from_user_id = 2 AND vdul.to_user_id = 24))
LEFT JOIN vrm_document AS vd ON vdul.vrm_document_id = vd.vrm_document_id
WHERE vd.vrm_document_type_id != 1
DB Fiddle link:
https://www.db-fiddle.com/f/f4es4LDfFE7HUMrnSPbJKw/0
Update DB fiddle to include the user_ids in the JOIN statement:
https://www.db-fiddle.com/f/f4es4LDfFE7HUMrnSPbJKw/2

You need to add the user IDs to the join condition, so you only get documents for the same users.
SELECT vdul.*, vd.title, vd.description, vduu.vrm_document_user_upload_id, vduu.document_path
FROM vrm_document_user_link AS vdul
LEFT JOIN vrm_document_user_upload AS vduu
ON vdul.vrm_document_id = vduu.vrm_document_id
AND vdul.to_user_id = vduu.to_user_id
AND vdul.from_user_id = vduu.from_user_id
LEFT JOIN vrm_document AS vd
ON vdul.vrm_document_id = vd.vrm_document_id
AND vd.vrm_document_type_id != 1
WHERE vdul.from_user_id = 2
AND vdul.to_user_id = 24

Related

Else is not running in mysql Query

I have below query. In this I have yes and no case.
yes is accessing but else part is not working . Please have a look on this.
SELECT SalesChannel.name , count(Transaction.category_id) as count, (case when (Transaction.no_of_units > 0 and Transaction.mop > 0) THEN 'yes' ELSE 'No' END) AS Is_Present from outlets Outlet inner join transactions Transaction on Outlet.id = Transaction.outlet_id inner join sale_channels SalesChannel on SalesChannel.id = Outlet.sale_channel_id group by SalesChannel.name
the output should be as below
KU Electrical
Yes 6 2
No 1 2
6 is counter of KU and Yes refers the presence,similarly No is non presence of KU
select SalesChannel.name ,
Transaction.category_id,
count(Transaction.category_id) as count,
from outlets Outlet inner join transactions Transaction on Outlet.id = Transaction.outlet_id inner join sale_channels SalesChannel on SalesChannel.id = Outlet.sale_channel_id group by SalesChannel.name
below are three tables which i used
1. transactions
CREATE TABLE IF NOT EXISTS `transactions` (
`id` int(11) NOT NULL,
`zone_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`sub_category_id` int(11) NOT NULL,
`brand_id` int(11) NOT NULL,
`model_id` int(11) NOT NULL,
`outlet_id` int(11) NOT NULL,
`no_of_units` int(11) NOT NULL,
`mop` decimal(10,2) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `transactions`
--
INSERT INTO `transactions` (`id`, `zone_id`, `state_id`, `city_id`, `category_id`, `sub_category_id`, `brand_id`, `model_id`, `outlet_id`, `no_of_units`, `mop`) VALUES
(1, 2, 2, 2, 2, 1, 1, 1, 1, 3, '6.00'),
(2, 2, 2, 2, 2, 1, 1, 1, 1, 3, '6.00'),
(3, 1, 1, 1, 1, 1, 1, 1, 1, 4, '2.00'),
(4, 2, 2, 2, 1, 1, 1, 1, 2, 4, '2.00');
2.outlets
CREATE TABLE IF NOT EXISTS `outlets` (
`id` int(11) NOT NULL,
`outlet_code` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`zone_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
`sale_channel_id` int(11) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `outlets`
--
INSERT INTO `outlets` (`id`, `outlet_code`, `name`, `zone_id`, `state_id`, `city_id`, `sale_channel_id`, `is_active`, `created`, `modified`) VALUES
(1, '1508', 'Ashok electricals', 2, 2, 2, 1, 1, '2016-10-03 00:00:00', '2016-10-03 00:00:00'),
(2, '1233', 'vinayak electricals', 1, 1, 1, 2, 1, '2016-10-04 00:00:00', '2016-10-04 00:00:00');
3. sale_chennals
CREATE TABLE IF NOT EXISTS `sale_channels` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `sale_channels`
--
INSERT INTO `sale_channels` (`id`, `name`, `is_active`, `created`, `modified`) VALUES
(1, 'KU', 1, '2016-10-03 00:00:00', '2016-10-03 00:00:00'),
(2, 'Electricals', 1, '2016-10-04 00:00:00', '2016-10-04 00:00:00');
There is no data in tables that match for the else condition. Your condition is that "Transaction.no_of_units >0 AND Transaction.mop >0" that is not match in table value of both fields are greater than 0.
Otherwise, else condition works fine.
You are aggregating your data so as to get one row per SalesChannel.name. There may be some transaction records that result in 'Yes' and others in 'No' for a SalesChannel.name, so what then is Is_Present supposed to be?
Another issue with your query is that the sale channels are in a table. There are currently two of them, but there could be three or four or thousands sometime. A SQL query doesn't produce a result with a variable number of columns. The columns must be known beforehand. So a possible result could look like this:
Name Yes No
KU 6 1
Electrical 2 2
because you know you want it to be Yes or No only, no matter how many channels.
The query:
select
sc.name,
count(case when t.no_of_units > 0 and t.mop > 0 then 1 end) as yes,
count(case when t.no_of_units <= 0 or t.mop <= 0 then 1 end) as no
from sale_channels sc
join outlet o on o.sale_channel_id = sc.id
join transactions t on t.outlet_id = o.id;

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

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

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.