简体   繁体   中英

Using GROUP_CONCAT with FIND_IN_SET in mysql WHERE clause

I have this query and want get appointment data from the table using student email but it get this error Unknown column 'stu' in 'where clause'

select a.*, GROUP_CONCAT(e.value) as stu FROM wp_ea_appointments a join
wp_ea_fields e on a.id = e.app_id WHERE a.date > DATE('2019-02-14') AND
FIND_IN_SET('jan@gmail.com' , stu ) GROUP BY a.id

FIND_IN_SET condition should be contained in HAVING statement instead of WHERE statement because you want to filter data after grouping

SELECT a.*, 
    GROUP_CONCAT(e.value) as stu 
FROM wp_ea_appointments a 
JOIN wp_ea_fields e ON a.id = e.app_id 
WHERE a.date > DATE('2019-02-14')
GROUP BY a.id
HAVING FIND_IN_SET('jan@gmail.com', stu) 

You can try using subquery

select * from
(
select a.*, GROUP_CONCAT(e.value) as stu FROM wp_ea_appointments a join
wp_ea_fields e on a.id = e.app_id WHERE a.date > DATE('2019-02-14') 
GROUP BY a.id
)A where FIND_IN_SET('jan@gmail.com' , stu ) 

Use a HAVING clause, but phrase the logic correctly:

SELECT a.*, GROUP_CONCAT(e.value) as stu
FROM wp_ea_appointments a JOIN
     wp_ea_fields e 
     ON a.id = e.app_id
WHERE a.date > DATE('2019-02-14')
HAVING SUM( e.value = 'jan@gmail.com' ) > 0;

There is no reason to use string concatenation to check whether the value exists. The string comparisons are more expensive and less clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM