Sql query - Cant select the max value of a row - mysql

I have this query that showing items in my site.
$sql = "
select p.id
, p.name
, p.logo
, p.short_description
, c.Parent_category
, IF(d.commission_name = 'percent'
, CONCAT(FORMAT(d.action, 2)/2 ,' %')
, CONCAT(FORMAT(d.action,2)/2,' €')) as comms
, GROUP_CONCAT(c.category_name SEPARATOR ',') as category_names
from eshop p
join eshop_cat c
on p.id = c.eshop_id
join eshop_commissions d
on p.id = d.eshop_id
where c.Parent_category = 'fashion'
and p.sites = 1
GROUP
BY d.action DESC
";
The problem is here
IF(d.commission_name = 'percent', CONCAT(FORMAT(d.action, 2)/2 ,' %') ,
CONCAT(FORMAT(d.action,2)/2,' €'))
i need only the biggest value of each eshop id. i tryied with this
IF(d.commission_name = 'percent', CONCAT(FORMAT(max(d.action), 2)/2 ,' %') ,
CONCAT(FORMAT(max(d.action),2)/2,' €'))
but its not working
For example i have 2 entries with the same eshop id
How can i receive only 1 commission that will be the biggest?
eshop_id commission_name action
1 percent 20 (%)
1 fixed_amount 30 (euro)
EDITED
CREATE TABLE `eshop` (
`id` int(11) NOT NULL,
`name` text NOT NULL,
`logo` text NOT NULL,
`short_description` text NOT NULL,
`sites` tinyint(1) NOT NULL,
`url` text NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`summary` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `eshop_commissions` (
`commission_name` text NOT NULL,
`eshop_id` int(11) NOT NULL,
`action` decimal(10,2) NOT NULL,
`subaction` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `eshop_cat` (
`eshop_id` int(11) NOT NULL,
`category_name` text NOT NULL,
`Parent_category` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `eshop_commissions` (`commission_name`, `eshop_id`, `action`, `subaction`) VALUES
('percent', 100, '12.00', '12.00'),
('fixed_amount', 100, '15.00', '15.00'),
('percent', 100, '5.00', '5.00'),
('percent', 100, '2.00', '2.00');
INSERT INTO `eshop` (`id`, `name`, `logo`, `short_description`, `description`, `sites`, `url, `timestamp`, `summary`) VALUES
(100, 'Tokotoukan', 'logo-tokotoukan.gif', '<p>\r\n !</p>\r\n', '<p>\r\n <font face=\"arial\" size=\"2\">Τo TOKOTOUKAN </font></p>\r\n', 1, 'http://www.com', ''2017-07-07 17:39:59', '15,00%');
INSERT INTO `eshop_cat` (`eshop_id`, `category_name`, `Parent_category`) VALUES
(100, 'fashion', 'fashion');

Related

How can I group_concat this mysql fields

I have this MySQL Query:
SELECT a.orcidid
, GROUP_CONCAT(distinct a.`from` SEPARATOR '<>' ) as StartDate
, GROUP_CONCAT(distinct a.`to` SEPARATOR '<>' ) as EndDate
from orcidaffils a
GROUP BY a.orcidid ;
For this DATA Table:
CREATE TABLE `orcidaffils` (
`recid` int(11) NOT NULL AUTO_INCREMENT,
`affil` varchar(6000) DEFAULT NULL,
`orcidid` varchar(100) DEFAULT NULL,
`city` varchar(100) DEFAULT NULL,
`country` varchar(100) DEFAULT NULL,
`from` date DEFAULT NULL,
`to` date DEFAULT NULL,
PRIMARY KEY (`recid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of orcidaffils
-- ----------------------------
INSERT INTO `orcidaffils` VALUES ('2', 'Graz University of Technology', '0000-0004-1034-5187', 'Graz', 'AT', '2010-01-01', null);
INSERT INTO `orcidaffils` VALUES ('3', 'Ecole Polytechnique', '0000-0004-1034-5187','Palaiseau', 'FR', '2008-09-01', '2010-07-01');
INSERT INTO `orcidaffils` VALUES ('4', 'University of Würzburg', '0000-0004-1034-5187', 'Wurzburg', 'DE', '2005-09-01', '2007-12-01');
No I would like to get this output:
The question is how to group_concat that the beginndate and the enddate is merged together per affliliation.
2010-01-01-now<>2008-01-09 to 2010-01-07<>2005-01-09 to 2007-01-12
thanks for any usefull advice.
As per the image you've mentioned
you could try something like this:
SELECT a.orcidid ,
GROUP_CONCAT(a.`affil` SEPARATOR '<>' )
, GROUP_CONCAT(CONCAT(a.`from`, ' to ', IFNULL(a.`to`,'now')) SEPARATOR '<>' ) AS StartDate
FROM orcidaffils a
GROUP BY a.orcidid ;

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;

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

MySQL Sub Query takes long time to respond

I've created 3 tables imei, post and view. I've some 1000 records in all the 3 tables. Now when I execute the b/m query, it tooks very long to respond.
Table design & sample data are given below:
CREATE TABLE IF NOT EXISTS `imei` (
`imei_id` int(5) NOT NULL AUTO_INCREMENT,
`imei_no` varchar(30) NOT NULL,
`imei_net` varchar(30) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`imei_id`),
UNIQUE KEY `imei_no` (`imei_no`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1346 ;
CREATE TABLE IF NOT EXISTS `post` (
`post_id` int(5) NOT NULL AUTO_INCREMENT,
`post_title` varchar(60) NOT NULL,
`post_desc` varchar(500) NOT NULL,
`post_author` varchar(30) NOT NULL DEFAULT 'Admin',
`user_id` int(10) NOT NULL DEFAULT '1',
`date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=876 ;
CREATE TABLE IF NOT EXISTS `view` (
`view_id` int(5) NOT NULL AUTO_INCREMENT,
`post_id` int(11) NOT NULL,
`imei_id` varchar(30) NOT NULL,
`status` varchar(10) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`view_id`),
UNIQUE KEY `imei_id` (`imei_id`,`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13706 ;
Values Inside table:
IMEI:
INSERT INTO `imei` (`imei_id`, `imei_no`, `imei_net`, `date`) VALUES
(1, '123456789012345', 'Airtel', '2015-08-06 07:39:47'),
(2, '234567890123456', 'Aircel', '2015-08-06 06:08:33')
POST:
INSERT INTO `post` (`post_id`, `post_title`, `post_desc`, `post_author`, `user_id`, `date`) VALUES
(1, 'NSC Rate Down', 'NSC rates are getting down from today', 'Admin', 1, '2015-07-08 05:29:54'),
(2, 'NCDEX offers cashback', 'NCDEX offers cashback for the previous users', 'Admin', 1, '2015-07-08 05:30:01')
VIEW:
INSERT INTO `view` (`view_id`, `post_id`, `imei_id`, `status`, `date`) VALUES
(1, 1, '1', '1', '2015-08-08 05:04:38'),
(7, 2, '1', '1', '2015-08-08 07:55:25')
Query to Execute:
SELECT
*
FROM
(
SELECT
i.imei_id,
i.imei_no,
p.post_id,
p.post_title,
p.post_desc,
p.date,
1 AS STATUS
FROM
imei i,
post p,
VIEW v
WHERE
i.imei_id = v.imei_id
AND p.post_id = v.post_id
AND i.imei_no = 356554064098771
UNION
SELECT
i.imei_id,
i.imei_no,
p.post_id,
p.post_title,
p.post_desc,
p.date,
0 AS STATUS
FROM
imei i,
post p
WHERE
i.imei_no = 356554064098771
AND p.post_id NOT IN (
SELECT
v.post_id
FROM
imei i,
post p,
VIEW v
WHERE
p.post_id = v.post_id
AND v.imei_id = (
SELECT
i.imei_id
FROM
imei i
WHERE
imei_no = 356554064098771
)
)
) AS temp
WHERE
date >= DATE_SUB(
(
SELECT
date
FROM
imei
WHERE
imei_no = 356554064098771
),
INTERVAL 1 WEEK
)
ORDER BY
date DESC
try this query SELECT post_id,post_title,post_desc,date,if((post_id in (SELECT post_id FROM view WHERE imei_id = (SELECT imei_id FROM imei WHERE imei_no=865645026396909))),1,0) as status FROM post

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