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
Related
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
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
.................................
I am trying to filter results based on the name assigned on count() and get this:
Unknown column 'total_submissions' in 'where clause'
SELECT SQL_CALC_FOUND_ROWS patient.*,count(patient_data.id) as total_submissions
FROM patient
LEFT JOIN patient_data ON (patient_data.patient_id = patient.id AND patient_data.date_finished IS NOT NULL)
WHERE patient.doc_id = 2 AND total_submissions = 5
GROUP BY patient.id
ORDER BY patient.id DESC
LIMIT 0,40
After more research I did find out about not being able to use a column alias in the WHERE but I am unsure how to execute this query then. I assume it's possible but how would I be able to filter the results based on the count() calculation of the query?
total_submissions is a column alias and the result of an aggregation function. You need to do that check in a havingclause:
SELECT SQL_CALC_FOUND_ROWS p.*, count(pd.id) as total_submissions
FROM patient p LEFT JOIN
patient_data pd
ON pd.patient_id = p.id AND pd.date_finished IS NOT NULL
WHERE p.doc_id = 2
GROUP BY p.id
HAVING total_submissions = 5
ORDER BY p.id DESC
LIMIT 0, 40;
Notes:
Table aliases make the query easier to write and to read.
The condition on doc_id should still be in the WHERE clause.
You can't use column alias in where clause because the precedence in sql evaluation don't let the db engine know the alias name when evaluate the where clause
First is evaluated the FROM clase then the WHERE clause and after the SELECT cluase ..
In your case you have an aggregation function related to yu alias and this can be evaluated only after the group by is performed, pratically at the end of query process
for this reason there is a proper filter based on HAVING that work on the result of the aggreated query
SELECT SQL_CALC_FOUND_ROWS patient.*, count(patient_data.id) as total_submissions
FROM patient
LEFT JOIN patient_data ON (patient_data.patient_id = patient.id AND patient_data.date_finished IS NOT NULL)
WHERE patient.doc_id = 2
GROUP BY patient.id
HAVING total_submissions = 0
ORDER BY patient.id DESC
LIMIT 0,40
Im am trying to create a query that joins on some data for each row of the main query, but I do not know how to get around the issue "Unknown column 'cm.index' in 'where clause'". How can I pass a column value of the parent query row to the sub query?
Each row in the parent query has an index integer. I want to count the number of channel_members that have a consumption index greater than the index of each message.
Here is a sample db
SELECT read_count.*, cm.*
FROM chat_messages as cm
JOIN (SELECT b.chat_channel_id, Count(b.chat_channel_id) AS members_read
FROM channel_members b
WHERE b.consumption_index >= cm.index
GROUP BY b.chat_channel_id) read_count
ON cm.channel_id = read_count.chat_channel_id
WHERE cm.channel_id=5;
A subquery that you're joining with is not a correlated subquery, so you can't pass columns from the main query into it, they have to be related in the ON condition.
You should change the subquery to include cm.index in the grouping. Then you can join on that.
SELECT cm.*, SUM(rc.members_read) AS members_read
FROM chat_messages AS cm
JOIN (SELECT chat_channel_id, consumption_index, COUNT(*) AS members_read
FROM channel_members
GROUP BY chat_channel_id, consumption_index) AS rc
ON cm.channel_id = rc.chat_channel_id AND rc.consumption_index >= cm.index
WHERE cm.channel_id = 5
Or you could do it as a real correlated subquery, which goes in the SELECT list.
SELECT cm.*,
(SELECT COUNT(*)
FROM channel_members AS b
WHERE b.chat_channel_id = cm.channel_id AND b.consumption_index = cm.index) AS members_read
FROM chat_messages AS cm
WHERE cm.channel_id = 5
I have this query, it is giving me error
Operand Should contains one column. But i need two columns for now . Can anybody help me out
SELECT `business`.`id` AS business_id,
`business`.`name` AS business_name,
`business`.`address`,
`business`.`address2`,
`business`.`city`,
`business`.`state`,
`business`.`zipcode`,
`business`.`lat`,
`business`.`lon`,
`service`.`id` AS ser_id,
`service`.`name` AS service_name,
(SELECT price, `price_verified`.`comments`
FROM `price_verified`
LEFT JOIN `price`
ON `price_verified`.`price_id` = `price`.`id`
WHERE `price`.`service_id` = ser_id
AND `price_verified`.`status` = 1
ORDER BY `price_verified`.`date_verified` DESC
LIMIT 1)
FROM service
LEFT JOIN `business` ON `service`.`business_id` = `business`.`id`
WHERE `service`.`business_id` = 1
Thanks
AS the error message says you can only have one result column in your sub-query.
either you have to concatenate the sub query result or have two sub queries for each column.
like:
(SELECT concat(price,`price_verified`.`comments`) as result
FROM `price_verified` LEFT JOIN `price` ON `price_verified`.`price_id`= `price`.`id` \n\
WHERE `price`.`service_id`=ser_id AND `price_verified`.`status`= 1 ORDER BY `price_verified`.`date_verified` DESC LIMIT 1)