This question already has answers here:
SELECT DISTINCT and ORDER BY in MySQL
(2 answers)
Closed 3 years ago.
I have two tables clients & exchange. I want to get clients id by running left join query. But when I run the query it throws an error.
select distinct
`clients`.`id` as `client_id`
from `clients`
left join `exchange`
on `clients`.`id` = `exchange`.`client_id`
where
`clients`.`iex_status` = 'Active'
order by
`exchange`.`validity_to` desc
error:
add exchange.validity_to this column into selection otherwise it will throw this error validity_to is not in SELECT list; this is incompatible with DISTINCT
select distinct
clients.id as client_id,exchange.validity_to
from clients
left join exchange
on clients.id = exchange.client_id
where
clients.iex_status = Active
order by
exchange.validity_to desc
But from your screen shot it seems you used parenthesis after distinct thats why you got the error
Hope you doing well, i have checked your query but found 2 diff. points
1 : "select distinct clients.id as client_id from clients left join exchange on clients.id = exchange.client_id where clients.iex_status = 'Active' order by exchange.validity_to desc "
You show this query in first and showing error in your query
2 : you are using "(" in your query that you have executed in sql i think your first query is right that will give you right result.
so please do not use ( ) in distinct fields.
thanks
As per your image attached you can modify alias out of braces as -
select distinct
(`clients`.`id` as `client_id`) as 'client_id'
from `clients`
left join `exchange`
on `clients`.`id` = `exchange`.`client_id`
where
`clients`.`iex_status` = 'Active'
order by
`exchange`.`validity_to` desc
Related
This question already has answers here:
Can you use an alias in the WHERE clause in mysql?
(5 answers)
Closed 3 years ago.
I have multiple tables with data on some clients. What I want to achieve is to output the amount that a certain client was billed for, in the first month he was billed.
So I run the code similar to the one bellow:
SELECT company,clientid,COALESCE (signed.value,reactivated.value) as 'Activation' , Amount FROM `tblclients`
LEFT JOIN tblcustomfieldsvalues as signed ON tblclients.clientid = signed.relid and signed.fieldid = 5
LEFT JOIN tblcustomfieldsvalues as reactivated ON tblclients.userid = reactivated.relid and reactivated.fieldid = 27
LEFT JOIN (
SELECT clientid,sum(total) as Amount FROM tblinvoices
WHERE month(invoicedate)=month(Activation) Group by clientid) as f on tblclients.clientid = f.clientid
My problem is that when I do the last join it gives an error : Unknown column 'Activation' in 'where clause'.
If I switch that to current_date the rest of the query works.
Any idea on how to make this work ?
Later edit: I might have oversimplified the query, I also have a COALESCE
You can try below -
SELECT company,clientid,activated.value as Activation , Amount
FROM `tblclients`LEFT JOIN tblcustomfieldsvalues as signed ON tblclients.clientid = signed.relid and signed.fieldid = 5
LEFT JOIN
( SELECT clientid,sum(total) as Amount
FROM tblinvoices Group by clientid
) as f on tblclients.clientid = f.clientid and month(invoicedate)=month(Activation)
This question already has answers here:
MySQL : isn't in GROUP BY
(5 answers)
Closed 3 years ago.
I have the following query:
SELECT cn.id, cn.title, cn.type, cn.status FROM (
SELECT v.concert_id as concert_id, SUM(v.position_votes + v.support_votes) as votes
FROM (
SELECT q.concert_id as concert_id, q.position_id as position_id, q.position_votes as position_votes, SUM(q.votes_up + q.votes_down) as support_votes
FROM (
SELECT qcs.id AS concert_id, p.id AS position_id, p.votes AS position_votes, IF(s.votes_in_favor <=> null, 0, s.votes_in_favor) AS votes_up, IF(s.votes_not_in_favor <=> null, 0, s.votes_not_in_favor) AS votes_down
FROM (
SELECT concert_id AS id
FROM positions p
WHERE p.content LIKE '%%'
GROUP BY concert_id
)
AS qcs
JOIN positions p
ON p.concert_id = qcs.id
LEFT JOIN supports s
ON s.position_id = p.id
) AS q
GROUP BY q.position_id
) as v
GROUP BY v.concert_id
) as r
JOIN concerts cn on cn.id = r.concert_id
ORDER BY r.votes DESC, cn.created_at DESC
When I made that query directly into MySQL I get the desired results. But when I put that query using DB, for example:
$query = "...alll_the_previous_query";
$result = DB::select(DB::raw($query));
I got the following error:
local.ERROR: SQLSTATE[42000]: Syntax error or access violation: 1055 'q.concert_id' isn't in GROUP BY ...the rest of the query
I know that a way to avoid this is to change the database configuration in Laravel and change the strict to false.
But that is not an option.
What is wrong with my query when I passed it to Laravel?
You can add the q.concert_id to the group by. Instead of:
GROUP BY q.position_id
Use:
GROUP BY q.concert_id, q.position_id
Hi I need to Order using count from another table. i found this great example, im using it as model for a query i need. SQL - How To Order Using Count From Another Table
The model im using for query is:
SELECT bloggers.*, COUNT(post_id) AS post_count
FROM bloggers LEFT JOIN blogger_posts
ON bloggers.blogger_id = blogger_posts.blogger_id
GROUP BY bloggers.blogger_id
ORDER BY post_count
But i have a syntax problem in mine, i guess, im trying to replace the next query, with the one that counts another table... but i cant manage to do it. Original query:
$res3=$db->execute_query("select id,scode,sname from ".TABLE_PREFIX."states where ccode=? order by sname asc",array($country));
Trying to replace with this query..
$res3=$db->execute_query("select ".TABLE_PREFIX."states.* , COUNT(".TABLE_PREFIX."items.state) AS state_count FROM ".TABLE_PREFIX."states LEFT JOIN ".TABLE_PREFIX."items ON ".TABLE_PREFIX."states.id = ".TABLE_PREFIX."items.state GROUP BY ".TABLE_PREFIX."states.id ORDER BY state_count DESC",array($country));
Try this:
$res3=$db->execute_query("select a.* , COUNT(b.state) AS state_count FROM states a
LEFT JOIN items b ON a.id = b.state
GROUP BY a.id
ORDER BY state_count DESC",array($country));
Some sql query gives me the following result:
As you can see, it already has GROUP BY.
So what I need? I need to group it again (by treatment_name) and count rows for each group. See more details on screenshot.
Here is full query:
SELECT
treatment_summaries.*
FROM `treatment_summaries`
INNER JOIN
`treatments`
ON
`treatments`.`treatment_summary_id` = `treatment_summaries`.`id`
AND
(treatment <> '' and treatment is not null)
INNER JOIN
`treatment_reviews`
ON
`treatment_reviews`.`treatment_id` = `treatments`.`id`
INNER JOIN
`conditions_treatment_reviews`
ON
`conditions_treatment_reviews`.`treatment_review_id` = `treatment_reviews`.`id`
INNER JOIN
`conditions` ON `conditions`.`id` = `conditions_treatment_reviews`.`condition_id`
INNER JOIN `conditions_treatment_summaries` `conditions_treatment_summaries_join`
ON
`conditions_treatment_summaries_join`.`treatment_summary_id` = `treatment_summaries`.`id`
INNER JOIN `conditions` `conditions_treatment_summaries`
ON `conditions_treatment_summaries`.`id` = `conditions_treatment_summaries_join`.`condition_id`
WHERE
`conditions`.`id` = 9
AND `conditions`.`id` IN (9)
AND (latest_review_id is not null)
GROUP BY
treatment_reviews.id
ORDER BY
treatment_summaries.reviews_count desc
LIMIT 20 OFFSET 0
Maybe there is another issue, cause GROUP BY should not leave same lines (for given column), but anyway you can wrap it like this:
SELECT * FROM ( YOUR_SQL_SELECT_WITH_EVERYTHING ) GROUP BY id
So the result you get will behave as another table and you can do all operations like GROUP BY again.
im trying to generate a report using CodeIgniter and Datatables.net .
Now i'm trying to the amount of closed jobs (its a human resources system). I used to query all jobs and in PHP do a foreach and then doing the calcs.
Because im want to use all the features of Datatables (sorting specifically) im trying to do all the calcs in mySQL.
The problem is: the second subquery is very very very slow.
SELECT
jobs.jobs_id, clients.nome_fantasia, concat_ws(' ', user_profiles.first_name, user_profiles.last_name) as fullname,
jobs.titulo_vaga, jobs.qtd_vagas, company.name as nome_company, jobs_status.name as status_name, DATEDIFF(NOW(), jobs.data_abertura) as date_idade,
(select count(job_cv.jobs_id) from job_cv where job_cv.jobs_id = jobs.jobs_id) as qtd_int,
(select count(distinct job_cv.user_id) from job_cv_history join job_cv on job_cv.job_cv_id = job_cv_history.job_cv_id where job_cv_history.status = '11' and job_cv.jobs_id = jobs.jobs_id ) as fechadas
FROM (jobs)
JOIN clients ON lients.clients_id=jobs.clients_idJOIN user_profiles ON jobs.consultor_id=user_profiles.user_id
JOIN jobs_status ON jobs.status=jobs_status.jobs_status_id
JOIN company ON jobs.company_id=company.company_id
LIMIT 50
Some one can help me? I can provide more information if its needed.
UPDATE
The idea to use JOIN instead SELECT work with the first subquery but with the second one not, there a way to pass a 'variable' to use inside the subquery? Like the current jobs_id?
UPDATE AGAIN
This line works fine by itself. But inside the subquery take about a minute with worng values
SELECT job_cv.jobs_id,count(distinct job_cv.user_id) AS fechadas
FROM job_cv_history
JOIN job_cv
ON job_cv.job_cv_id = job_cv_history.job_cv_id
WHERE job_cv_history.status = '11'
GROUP BY job_cv.jobs_id
It is not subquery that is slow. It's the fact, that you're executing these subqueries for each row returned from outer query. Move these to joins instead, and you should observe increase in performance.
SELECT
jobs.jobs_id, clients.nome_fantasia, concat_ws(' ', user_profiles.first_name, user_profiles.last_name) as fullname,
jobs.titulo_vaga, jobs.qtd_vagas, company.name as nome_company, jobs_status.name as status_name, DATEDIFF(NOW(), jobs.data_abertura) as date_idade,
qtd.qtd_int,
fechadas.fechadas
FROM (jobs)
JOIN clients ON lients.clients_id=jobs.clients_idJOIN user_profiles ON jobs.consultor_id=user_profiles.user_id
JOIN jobs_status ON jobs.status=jobs_status.jobs_status_id
JOIN company ON jobs.company_id=company.company_id
JOIN (
SELECT jobs_id, count(jobs_id) AS qtd_int FROM job_cv GROUP BY jobs_id
) AS qtd ON qtd.jobs_id = jobs.jobs_id
JOIN (
SELECT job_cv.user_id, count(distinct job_cv.user_id) AS fechadas
FROM job_cv_history
JOIN job_cv
ON job_cv.job_cv_id = job_cv_history.job_cv_id
WHERE job_cv_history.status = '11'
GROUP BY job_cv.user_id
) AS fechadas ON job_cv.jobs_id = jobs.jobs_id
LIMIT 50
You may try to create these indexes:
ALTER TABLE `job_cv` ADD INDEX `job_cv_cindex` (`job_cv_id` ASC, `jobs_id` ASC, `user_id` ASC);
ALTER TABLE `job_cv_history` ADD INDEX `job_cv_history_cindex` (`job_cv_id` ASC, `status` ASC);
use Joins instead of sub queries. It significantly improves the performance in MySql.
try to use Left join on your case and see if performance improves or not