简体   繁体   中英

Using selected columns in a WHERE EXISTS query in MySQL

I have a table which is related to itself, with columns vin, type and sn. I want to find all rows with type of 2 that have only one row with type of 1; I tried this:

 select count(*) as aggregate 
 from `data` as `t1` 
 where `type` = 2 
   and `last_service` < DATE_SUB(now(), INTERVAL 12 MONTH) 
   and exists (
                select count(*) as data.count 
                from `data` 
                where count=1 
                  and `type` = 1
               )

but I keep getting the following error:

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' .count from data where count=1 and type = ?)' at line 1 .

you cannot assign data to table column like that. Try

select count(*) as count from data where count=1 and type = 1


select count(*) as count from data having count(*) = 1 and type = 1

There is syntax error because you use alias as complex identifier: as data.count . Try as data_count instead.

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