Using Inline Query Field in Where Condition - mysql

I have gone through this solution Using Inline Query Alias in Where clause outside of inline Query but its not working for below query
select `leads`.*, `departmentdata`.`name` as `department`,
(
select activitytype.activity_name
from activities inner
join activitytype on activitytype.id = activities.activity_type_id
where activities.leadid = leads.id
and activities.followup_date >= CURDATE()
order by activities.followup_date asc
limit 0,1
)temp1
from `leads`
left join `departmentdata` on `departmentdata`.`id` = `leads`.`department`
where activity_name = 'Email'
order by `leads`.`id` desc
i am still getting below error.
MySQL said: Documentation
#1054 - Unknown column 'activity_name' in 'where clause'
Any help?
Since this is a very big query so removed other fields. Below is the query without putting condition on activity_name fields.
But when i apply condition on activity_name field then i get above error.

See if moving your where to your inline select gives you your result.
I wonder if you need to join activitytype but can't really tell because I don't know what your expected outcome is and there is no test data.
select
`leads`.*,
`departmentdata`.`name` as `department`,
(
select
activitytype.activity_name
from
activities
inner join
activitytype
on
activitytype.id = activities.activity_type_id
where
activities.leadid = leads.id and
activities.followup_date >= CURDATE() and
activities.activity_name = 'Email'
order by
activities.followup_date asc
limit 0,1
) as temp1
from
`leads`
left join
`departmentdata`
on
`departmentdata`.`id` = `leads`.`department`
order by
`leads`.`id` desc

Related

Mysql nested select query inside having

Mysql says "Error Code: 1054. Unknown column 'ju.id' in 'where clause'"
Why I can't use the alias ju inside the nested select. Is there any issue the way I have ordered the query?
SELECT `ac`.`name`, COALESCE(SUM(tr.amount*ju.rate), 0) as amount
FROM `transactions` `tr`
LEFT JOIN `journals` `ju` ON `tr`.`journal_id` = `ju`.`id`
LEFT JOIN `accounts` `ac` ON `ac`.`id` = `tr`.`account`
WHERE `ju`.`txn_date` >= UNIX_TIMESTAMP('2021-01-01 00:00:00')
AND `ju`.`txn_date` <= UNIX_TIMESTAMP('2021-07-08 23:59:59')
AND `tr`.`type` = 'debit'
AND (`ac`.`bank` = 1 OR `ac`.`cash` = 1)
AND `ac`.`business` = 201
GROUP BY `ac`.`id`
HAVING ( SELECT tra.id
FROM transactions tra
LEFT JOIN accounts acc ON `acc`.`id` = `tra`.`account`
WHERE `tra`.`journal_id` = `ju`.`id`
AND `tra`.`type` = 'credit'
AND `acc`.`category` IN ('Sales Revenue','Other Income')
) IS NOT NULL;
I think the correct explanation is that the subquery after HAVING (between the parenthesis) make the alias "ju" in the top level query out of scope.
I've never used HAVING before, but my solution would be to add the "journals" table to the subquery with the needed criteria. But that really depends on what you want to query for.

How to add condition on virtual column in mysql?

I want to add a condition for the tbl_restaurant_featured_history.id column but I can't add that condition in where clause because It shows an error saying Unknown column 'featured' in 'where clause' and If I add a condition featured is not null in having clause It is returning 0 rows.
Below is the query before adding the condition
SELECT
DISTINCT(tbl_restaurant.id) as restaurant_id,
tbl_restaurant.name,
tbl_restaurant_featured_history.id as featured,
tbl_restaurant.min_order_amount,
tbl_restaurant.latitude as latitude,
tbl_restaurant.logo,
tbl_favourite_restaurant.id as is_fav,
tbl_restaurant.address as address,
IF(tbl_restaurant_timing.start_time <= '19:56:26' && tbl_restaurant.service = 'Available' && tbl_restaurant_timing.end_time >= '19:56:26', 'Open', 'Closed') AS availblity,
tbl_restaurant.longitude as longitude,
(
SELECT ROUND(AVG(tbl_rate_review.rate))
FROM tbl_rate_review
where tbl_rate_review.restaurant_id = tbl_restaurant.id
GROUP BY restaurant_id
) as avgrating,
(
SELECT ROUND(AVG(tbl_rate_review.rate), 2)
FROM tbl_rate_review
where tbl_rate_review.restaurant_id = tbl_restaurant.id
GROUP BY restaurant_id
) as rating,
111.045 * DEGREES(ACOS(COS(RADIANS(23.0266941)) * COS(RADIANS(latitude)) * COS(RADIANS(longitude) - RADIANS(72.6008731)) + SIN(RADIANS(23.0266941)) * SIN(RADIANS(latitude)))) AS distance_in_km
FROM tbl_restaurant
LEFT JOIN tbl_restaurant_featured_history ON tbl_restaurant_featured_history.restaurant_id = tbl_restaurant.id
LEFT JOIN tbl_restaurant_menu ON tbl_restaurant_menu.restaurant_id = tbl_restaurant.id AND tbl_restaurant_menu.status='Active'
LEFT JOIN tbl_favourite_restaurant ON tbl_favourite_restaurant.restaurant_id=tbl_restaurant.id AND tbl_favourite_restaurant.user_id=19
LEFT JOIN tbl_restaurant_timing ON tbl_restaurant_timing.restaurant_id = tbl_restaurant.id AND tbl_restaurant_timing.day = 'Saturday'
WHERE tbl_restaurant.status = 'Active'
HAVING distance_in_km <= 10
ORDER BY availblity DESC, distance_in_km ASC LIMIT 10, 10
And the output of this query
The query is poorly formated and hence rather hard to follow.
I can see this in the select clause:
tbl_restaurant_featured_history.id as featured
The where clause of a query just can't refer to an alias defined in the select clause. If you want to filter on this, then you need to use the column name (tbl_restaurant_featured_history.id) rather than the alias (featured):
where tbl_restaurant_featured_history.id is not null
The table tbl_restaurant_featured_history is LEFT joined to the table tbl_restaurant and this is why you get nulls in the results because some rows do not match the conditions of the ON clause that you have set.
If you want to add the condition:
tbl_restaurant_featured_history.id is not null
this means that you want only the matching rows and from your sample data I see that there is only 1 matching row.
In this case all you have to do is change the join to an INNER join:
.................................
FROM tbl_restaurant
INNER JOIN tbl_restaurant_featured_history ON tbl_restaurant_featured_history.restaurant_id = tbl_restaurant.id
.................................

MYSQL: Error Code: 1054. Unknown column in 'where clause'

I'm trying to pass a column from the outer query as shown below to the inner query in the WHERE clause and MySQL does not like it. I'm unsure how to rewrite this query to make it work.
The error message I am getting is Unknown column 'y.DateShipped' in where clause
What I am trying to do is to join to the row in the inner table with an EffectiveDate that is less than the DateShipped and also is the max EffectiveDate in the inner join (there can be multiple rows for the same group by with different EffectiveDate(s))
I would love to know how to get this working or rewrite it so that it will work. I am using MySQL 5.6, so I don't have window functions available otherwise I think that could work.
select
x.id,
y.id,
y.DateShipped
from Shipment y inner join
(select id, SourceId, DestinationId, SourcePPFContractId, EffectiveDate
from Relationship where EffectiveDate <= y.DateShipped order by
EffectiveDate desc limit 1) x
on x.DestinationId = y.DestinationCustomerId
and x.SourceId = y.OriginCustomerId
and x.SourcePPFContractId = y.OriginContractId;
The inner select (from Relationship) is executed first and then merged with the first select. That's why it doesn't work. You should move the DateShipped to the where clause of the first select:
select
x.id,
y.id,
y.DateShipped
from Shipment y inner join
(select id, SourceId, DestinationId, SourcePPFContractId, EffectiveDate
from Relationship order by
EffectiveDate desc limit 1) x
on x.DestinationId = y.DestinationCustomerId
and x.SourceId = y.OriginCustomerId
and x.SourcePPFContractId = y.OriginContractId
and x.EffectiveDate <= y.DateShipped;
You are attempting something called a lateral join -- and MySQL does not support those. Because you want only one column, you can use a correlated subquery:
select (select r.id
from Relationship r
where r.DestinationId = s.DestinationCustomerId and
r.SourceId = s.OriginCustomerId and
r.SourcePPFContractId = s.OriginContractId and
r.EffectiveDate <= s.DateShipped
order by r.EffectiveDate desc
limit 1
) as x_id,
s.id, s.DateShipped
from Shipment s ;
Note that I also changed the table aliases to be abbreviations for the table names -- so the query is easier to read.
you would need to list the shipment table in the sub query to be able to call it properly try:
select
x.id,
y.id,
y.DateShipped
from Shipment y inner join
(select id, SourceId, DestinationId, SourcePPFContractId, EffectiveDate
from Relationship, Shipment where EffectiveDate <= Shipment.DateShipped order by
EffectiveDate desc limit 1) x
on x.DestinationId = y.DestinationCustomerId
and x.SourceId = y.OriginCustomerId
and x.SourcePPFContractId = y.OriginContractId;

Order by clause is not working with group by in sql query

MYSQL query is getting data exactly as I want.But ORDER BY clause is not working.
But when I removed the GROUP BY from query then ORDER BY clause is work.
SELECT MESS. * , US. * , LF. *
FROM messages MESS
LEFT JOIN users AS US ON US.id = MESS.to_id
LEFT JOIN label_infos LF ON LF.user_id = MESS.to_id
WHERE MESS.frm_id =27
OR MESS.to_id =27
GROUP BY US.id
ORDER BY MESS.id DESC

How to access outer column values in mysql subquery?

In mysql I have this query
SELECT m.*
FROM members m
RIGHT JOIN (SELECT
IF(`from member_id`=1, `to member_id`, `from member_id`) as other_id, text, `date sent`
FROM message
WHERE ((`from member_id`=1 AND `to member_id`=m.id) OR (`to member_id`=1 OR `from member_id`=m.id))
ORDER BY `date sent` DESC
LIMIT 1
) as t on 1=1
ORDER BY t.`date sent` DESC
and I'm getting this error:
Unknown column 'm.id' in 'where clause'
How can I pass the members column value in the sub query select statement?
I am creating this sub query so it evaluates to 1 row, then I want to attach it to the right of the outer select statement.
Thanks.
You need to SELECT the from member_id/to member_id values in the subquery. Then, you can join the table m on the derived table where you will have access to the values.
) as t on t.`from member_id` = 1 AND t.`to member_id` = m.id
OR t.`to member_id` = 1 OR t.`from member_id` = m.id