I have this query which works perfectly:
SELECT
u.id
, u.mobile
, u.name
, (NOW() - u.authenticationTime) AS authenticateTimeDifference
, u.IP
, c.providerid
, c.requestid
, c.status
, u.port
FROM contacts c
LEFT JOIN users u ON u.id =
IF (
c.providerid = 2
, c.requestid
, c.providerid
) WHERE (
c.providerid = 2
AND c.status = 1
)
OR c.requestid = 2
ORDER BY authenticateTimeDifference
Now I wanted to only select DISTINCT u.name fields (or unique users) so I changed u.name to DISTINCT(u.name) but I am getting error:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'DISTINCT(u.name) ,
(NOW() - u.authenticationTime) AS au' at line 4
I also tried adding GROUP BY u.name but still no luck.
Can anybody tell how do I select unique names/users through above query ?
Thanks for the help
First, you need to use group by:
SELECT
u.id
, u.mobile
, u.name
, (NOW() - u.authenticationTime) AS authenticateTimeDifference
, u.IP
, c.providerid
, c.requestid
, c.status
, u.port
FROM contacts c
LEFT JOIN users u ON u.id =
IF (
c.providerid = 2
, c.requestid
, c.providerid
) WHERE (
c.providerid = 2
AND c.status = 1
)
OR c.requestid = 2
GROUP BY u.name
ORDER BY authenticateTimeDifference
Then you have to decide what to do with the other values. Should they show the lowest value, highest value, average, etc.? Since you want to group on the name only, you have to pick one for the fields not in the group by.
According to me Distinct must occur just after select. SO your query should be like this:-
SELECT DISTINCT u.id, u.mobile, u.name, (NOW() - u.authenticationTime) AS authenticateTimeDifference
, u.IP, c.providerid, c.requestid, c.status, u.port
FROM contacts c
LEFT JOIN users u ON u.id =
IF (c.providerid = 2, c.requestid, c.providerid)
WHERE (
c.providerid = 2
AND c.status = 1
)
OR c.requestid = 2
ORDER BY authenticateTimeDifference
Related
I'm getting this error, I am new to sql I don't get any solution regarding my problem, I would really Appreciate if someone can help get me rid of this error
SELECT job.jobStatusId,
job.customerId,
mazdoor.mazdoorName,
mazdoor.picture ,
job.mazdoorId,
job.workingHistoryId,
service.serviceName,
service.price ,
contractor.cnic ,
contractor.contractorId,
contractor.contractorName ,
SUM(CONCAT(Extract(HOUR From timeStamp) ,'.', Extract(MINUTE From timeStamp))*service.price*0.05 ) AS GRANDTOTAL ,
Date(job.timesStamp) AS Date
FROM job
INNER JOIN mazdoor ON mazdoor.mazdoorId = job.mazdoorId
INNER JOIN service ON service.serviceId = job.serviceId
INNER JOIN contractor ON mazdoor.contractorId = contractor.contractorId
WHERE job.jobStatusId = '3'
AND mazdoor.jobsCompleted>=1
AND mazdoor.contractorId = '$email'
GROUP BY contractor.cnic
--The column was misspelled
SELECT job.jobStatusId,
job.customerId,
mazdoor.mazdoorName,
mazdoor.picture ,
job.mazdoorId,
job.workingHistoryId,
service.serviceName,
service.price ,
contractor.cnic ,
contractor.contractorId,
contractor.contractorName ,
SUM(CONCAT(Extract(HOUR From timeStamp) ,'.', Extract(MINUTE From timeStamp))*service.price*0.05 ) AS GRANDTOTAL ,
Date(job.timeStamp) AS Date --< column name was wrong.
FROM job
INNER JOIN mazdoor ON mazdoor.mazdoorId = job.mazdoorId
INNER JOIN service ON service.serviceId = job.serviceId
INNER JOIN contractor ON mazdoor.contractorId = contractor.contractorId
WHERE job.jobStatusId = '3'
AND mazdoor.jobsCompleted>=1
AND mazdoor.contractorId = '$email'
GROUP BY job.jobStatusId,
job.customerId,
mazdoor.mazdoorName,
mazdoor.picture ,
job.mazdoorId,
job.workingHistoryId,
service.serviceName,
service.price ,
contractor.cnic ,
contractor.contractorId,
contractor.contractorName ,
Date(job.timeStamp)
`
-- and the non-aggregate fields has to be group by
Hi I have 8 million row data and need to optimize Mysql query to fetch a row from that data. I am using below query but its server response time is too high that creating issue in page loading speed
SELECT q.id
, q.title
, q.question
, q.price
, q.created
, q.userid
, q.duedate
, q.tags
, s.id subjectid
, sc.id subcategoryid
, s.title subject
, sc.title subcategory
, q.statusid
, (SELECT COUNT(id) FROM tbl_answers a WHERE a.questionid = q.id AND a.statusid = 1 AND a.deleted = 'N') q_num_answers
, u.username
, u.image
, u.gender
, (SELECT COUNT(id) FROM tbl_answers a WHERE a.userid = q.userid AND a.statusid = 1 AND a.deleted = 'N') num_answers
, (SELECT COUNT(id) FROM tbl_questions WHERE userid = q.userid AND statusid = 1 AND deleted = 'N') AS num_questions
, 0 amt_earned
, 0 amt_spent
, 0 num_sold
, (SELECT COUNT(ur.id) FROM tbl_users_ratings ur WHERE ur.userid = q.userid AND ur.deleted = 'N') u_num_ratings
, (SELECT COALESCE(SUM(ur.rating), 0) FROM tbl_users_ratings ur WHERE ur.userid = q.userid AND ur.deleted = 'N') u_score
FROM tbl_questions q
JOIN tbl_subjects s
ON q.subject = s.id
JOIN tbl_subjects sc
ON q.subcategory = sc.id
LEFT
JOIN tbl_users u
ON u.id = q.userid
WHERE q.deleted = '$show_deleted'
AND q.id = ?
LIMIT 1
These indexes may help. (I am assuming that id is the PRIMARY KEY of each table.)
ur: (deleted, userid, rating)
a: (deleted, statusid, userid)
a: (deleted, statusid, questionid)
Please provide EXPLAIN SELECT ....
Don't use COUNT(id) unless you need to check for id not being NULL. The usual way to write it is COUNT(*).
In one place you are checking for a provided values for deleted. In another, you hard code it. Perhaps wrong?
AND ur.deleted = 'N'
If the PRIMARY KEY for q is id, then this will lead to either 1 row or no row. What am I missing?
WHERE q.deleted = '$show_deleted'
AND q.id = ?
(There may be more tips. Please change the things I suggested and follow the suggestions from others. Then let's have another look.)
I am attempting to create a stored procedure but every time I try to apply it won't let me and throws the following error: Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' CREATE DEFINER=Admin#% PROCEDURE culls_&_deactivation() BEGIN D' at line 1
I have tried everything including running each part of the procedure and they all work. But sometimes the insert will fail and sometimes the create fails so I am not entirely sure what the issues are.
Also for reference I am using MySql 8.0.17
DELIMITER $$
CREATE DEFINER=`Admin`#`%` PROCEDURE `culls_and_deactivations`()
BEGIN
DROP TABLE IF EXISTS `metrics`.`tempvault`;
CREATE TABLE `metrics`.`tempvault`(
vault_date DATE DEFAULT NULL
, matterid varchar(32) DEFAULT NULL
, MatterName TEXT
, AccountName TEXT
, owner_REP TEXT
, valt TEXT
, mrr decimal(10,2) DEFAULT NULL
, GbHosted float DEFAULT NULL
, company_profile__c TEXT
, week_start_date DATE DEFAULT NULL
, week_end_date DATE DEFAULT NULL
, month_and_year varchar(30) default NULL
);
INSERT INTO metrics.tempvault
SELECT
CAST(scsdr.begin_date__c AS date)
, m.id
, m.Name AS MatterName
, a.Name AS AccountName
, CONCAT(u.firstname, ' ', u.lastname) AS owner
, "VAULT" AS Type
, NULL AS mrr
, dgh.GbHosted AS GbHosted
, a.company_profile__c
, du.week_start_date
, du.week_end_date
, du.month_and_year
FROM metrics.sf_matter__c m
INNER JOIN metrics.sf_cold_storage_date_range__c scsdr
ON scsdr.matter__c = m.id
INNER JOIN metrics.daily_gb_hosted dgh
ON dgh.matterid = m.id
#AND dgh.date_value = CAST(NOW() AS DATE)
AND dgh.date_value = DATE_ADD(CAST(scsdr.begin_date__c AS DATE), INTERVAL -1 DAY)
INNER JOIN metrics.daily_matter_contract_mapping dmcm
ON dmcm.matterid = m.id
AND dmcm.date_value = CAST(scsdr.begin_date__c AS DATE)
INNER JOIN metrics.sf_contract c
ON c.id = dmcm.contractid
INNER JOIN date_utility du
ON du.date_value = CAST(scsdr.begin_date__c AS DATE)
INNER JOIN metrics.sf_account a
ON a.id = c.billingaccount__c
LEFT JOIN metrics.sf_sf_user u
ON u.id = m.salesperson__c
WHERE 1=1
AND CAST(scsdr.begin_date__c AS date) >= '2018-01-01'
AND c.type__c = 'Transactional';
SELECT * FROM (
SELECT
CAST(m.deactivationdate__c AS DATE) AS Date
, m.id AS matterid
, m.Name AS MatterName
, a.Name AS AccountName
, CONCAT(firstname, ' ', lastname) AS owner
, "DEACTIVATION" AS Type
, mmmts.mrr AS mrr
, dgh.GbHosted AS GbHosted
, a.company_profile__c
, du.week_start_date
, du.week_end_date
, du.month_and_year
FROM metrics.sf_matter__c m
INNER JOIN metrics.daily_gb_hosted dgh
ON dgh.matterid = m.id
#AND dgh.date_value = CAST(NOW() AS DATE)
AND dgh.date_value = DATE_ADD(CAST(m.deactivationdate__c AS DATE), INTERVAL -1 DAY)
INNER JOIN metrics.daily_matter_contract_mapping dmcm
ON dmcm.matterid = m.id
#AND dmcm.date_value = CAST(NOW() AS DATE)
AND dmcm.date_value = CAST(m.deactivationdate__c AS DATE)
INNER JOIN metrics.sf_contract c
ON c.id = dmcm.contractid
INNER JOIN date_utility du
ON du.date_value = CAST(m.deactivationdate__c AS DATE)
INNER JOIN metrics.sf_account a
ON a.id = c.billingaccount__c
LEFT JOIN metrics.sf_sf_user u
ON u.id = m.salesperson__c
LEFT JOIN metrics.matter_monthly_mrr_time_series mmmts
ON mmmts.matter_id = m.id
AND mmmts.date_value = du.month_end_date
WHERE 1=1
AND CAST(m.deactivationdate__c AS DATE) >= '2018-01-01'
#AND gbHosted > 10
AND c.type__c = 'Transactional'
GROUP BY CAST(m.deactivationdate__c AS DATE), m.Name, a.Name
) AS t1
UNION
SELECT * FROM (
SELECT
MIN(CAST(d.dateadded__c AS DATE)) AS Date
, m.id AS matterid
, m.Name AS MatterName
, a.Name AS AccountName
, CONCAT(firstname, ' ', lastname) AS owner
, "CULL" AS Type
, mmmts.mrr AS mrr
, MAX(dgh.GbHosted) AS GbHosted
, a.company_profile__c
, du.week_start_date
, du.week_end_date
, du.month_and_year
FROM metrics.sf_matter__c m
INNER JOIN metrics.sf_dataset__c d
ON m.id = d.matter__c
AND d.data_size__c < 0
INNER JOIN metrics.daily_gb_hosted dgh
ON dgh.matterid = m.id
AND dgh.date_value = DATE_ADD(CAST(d.dateadded__c AS DATE), INTERVAL -1 DAY)
INNER JOIN metrics.daily_matter_contract_mapping dmcm
ON dmcm.matterid = m.id
AND dmcm.date_value = CAST(d.dateadded__c AS DATE)
INNER JOIN metrics.sf_contract c
ON c.id = dmcm.contractid
INNER JOIN date_utility du
ON du.date_value = CAST(d.dateadded__c AS DATE)
INNER JOIN metrics.sf_account a
ON a.id = c.billingaccount__c
LEFT JOIN metrics.sf_sf_user u
ON u.id = m.salesperson__c
LEFT JOIN metrics.matter_monthly_mrr_time_series mmmts
ON mmmts.matter_id = m.id
AND mmmts.date_value = du.month_end_date
WHERE 1=1
AND CAST(d.dateadded__c AS DATE) >= '2018-01-01'
AND data_size__c < 0
AND c.type__c = 'Transactional'
GROUP BY du.month_and_year, a.Name, m.Name
) AS t2
UNION
SELECT * FROM metrics.tempvault tv
#GROUP BY tv.month_and_year, tv.AccountName, tv.MatterName
UNION
SELECT * FROM(
SELECT
CAST(spc.createddate AS date)
, m.id AS matterid
, m.Name AS MatterName
, a.Name AS AccountName
, CONCAT(u.firstname, ' ', u.lastname) AS owner
, "VAULT" AS Type
, NULL AS mrr
, SUM(spc.datasize__c) AS GbHosted
, a.company_profile__c
, du.week_start_date
, du.week_end_date
, du.month_and_year
FROM metrics.sf_matter__c m
INNER JOIN metrics.sf_partialvault__c spc
ON spc.matter__c = m.id
INNER JOIN metrics.daily_matter_contract_mapping dmcm
ON dmcm.matterid = m.id
AND dmcm.date_value = CAST(spc.createddate AS DATE)
INNER JOIN metrics.sf_contract c
ON c.id = dmcm.contractid
INNER JOIN date_utility du
ON du.date_value = CAST(spc.createddate AS DATE)
INNER JOIN metrics.sf_account a
ON a.id = c.billingaccount__c
LEFT JOIN metrics.sf_sf_user u
ON u.id = m.salesperson__c
LEFT JOIN (
SELECT matterid as MATTERID, month_and_year AS MY
FROM metrics.tempvault
GROUP BY matterid, month_and_year
) AS tv ON tv.MATTERID = m.id AND tv.MY = du.month_and_year
WHERE 1=1
AND CAST(spc.createddate AS date) >= '2018-01-01'
AND c.type__c = 'Transactional'
AND tv.MATTERID IS NULL
AND tv.MY IS NULL
GROUP BY du.month_and_year, a.Name, m.Name
)AS t3;
DROP TABLE IF EXISTS metrics.tempvault;
END $$
DELIMITER ;
Try to avoid '&' in the name of procedure.
I have a problem with the count(*) alias when in insert it in Where...I receive the following error:
Error Code: 1054. Unknown column 'count' in 'where clause'
It is my understanding that sql reads from right to left and that is the reason for the error, but I do not know how to validate this so that I am only shown the fields that are found at the two points of the database.
this is my code...
SELECT COUNT(*) as count, interests.id, entity.id, entity.name, entity.entity_type, entity.city_country_province, entity.street_address, entity.user_id, entity.descript, entity.icon, city_country_province_type.city, city_country_province_type.province, city_country_province_type.country, entity.linkout, entity.map_lng, entity.map_lat
FROM ((interests INNER JOIN interest_entity ON interests.id = interest_entity.interet_id)
INNER JOIN entity ON interest_entity.entity_id = entity.id)
INNER JOIN city_country_province_type ON entity.city_country_province = city_country_province_type.id
WHERE ((interests.id)=9) AND count >= 10 AND count <= 20
Put the condition about the alias count into a HAVING clause
SELECT COUNT(*) as count, interests.id, entity.id, entity.name, entity.entity_type, entity.city_country_province, entity.street_address, entity.user_id, entity.descript, entity.icon, city_country_province_type.city, city_country_province_type.province, city_country_province_type.country, entity.linkout, entity.map_lng, entity.map_lat
FROM ((interests INNER JOIN interest_entity ON interests.id = interest_entity.interet_id)
INNER JOIN entity ON interest_entity.entity_id = entity.id)
INNER JOIN city_country_province_type ON entity.city_country_province = city_country_province_type.id
WHERE ((interests.id)=9)
HAVING
count >= 10 AND count <= 20
Your should grup by for get the proper related count ..use having for filter cont result (and remove unuseful () )
SELECT COUNT(*) as count
, interests.id
, entity.id
, entity.name
, entity.entity_type
, entity.city_country_province
, entity.street_address
, entity.user_id
, entity.descript
, entity.icon
, city_country_province_type.city
, city_country_province_type.province
, city_country_province_type.country
, entity.linkout
, entity.map_lng
, entity.map_lat
FROM interests INNER JOIN interest_entity ON interests.id = interest_entity.interet_id
INNER JOIN entity ON interest_entity.entity_id = entity.id
INNER JOIN city_country_province_type ON entity.city_country_province = city_country_province_type.id
WHERE interests.id=9
GROUP BY interests.id
, entity.id
, entity.name
, entity.entity_type
, entity.city_country_province
, entity.street_address
, entity.user_id
, entity.descript
, entity.icon
, city_country_province_type.city
, city_country_province_type.province
, city_country_province_type.country
, entity.linkout
, entity.map_lng
, entity.map_lat
HAVING count >= 10 AND count <= 20
really do not know if you can, but i I need the DATE VENC to be equal to '2013-02-02'.
the values of the column date_pay:
1-2013-01-01
2-2013-02-02
3-0000-00-00
4-0000-00-00
this is my query:
SELECT s.id,
s.name,
s.nro_s,
ts.cat,
SUM( ts.pryce ) AS deuda,
SUM( ts.pryce ) DIV ts.pryce AS c_p,
date_venc = (select max(date_pay) from c ) // the date in question
FROM s
INNER JOIN c
INNER JOIN ts
WHERE s.id = '123'
AND c.id = '123'
AND c.date_pay = '0000-00-00'
AND s.ts = ts.id_ts
Sorry for my english, is very basic.
Greetings.
Assuming date_venc is DATE a possible solution
select *
from s
where s.date_venc=
(select max(cast(SUBSTRING_INDEX(date_pay,'-',-3)as DATE))from c);
also check out sqlfiddle
http://sqlfiddle.com/#!2/64197/1
and your query should probably be modified to,
SELECT s.id,
s.name,
s.nro_s,
ts.cat,
SUM( ts.pryce ) AS deuda,
SUM( ts.pryce ) DIV ts.pryce AS c_p,
date_venc
FROM s
INNER JOIN c
INNER JOIN ts
WHERE s.id = '123'
AND c.id = '123'
AND c.date_pay = '0000-00-00'
AND s.ts = ts.id_ts
AND date_venc = (select max(cast(SUBSTRING_INDEX(date_pay,'-',-3)as DATE)) from c ) // the date in question