MYSQL计数查询错误

时间:2017-04-23 06:23:49

标签: mysql

Mysql查询:

SELECT `message`.`id` as `message_id`, 
`pet_info`.`id` as `pet_id`,
`pet_info`.`pet_hidenum` as `hidenum`,
`lostpets`.`pet_lost_date` as `pet_lost_date`,
`lostpets`.`type` as `status`,
`pet_images`.`img` as `img`,
COUNT(SELECT * FROM `message` WHERE `message`.`status` = 'not seen') as unread 
 FROM `message`
 LEFT JOIN `pet_info` ON `pet_info`.`id` = `message`.`pet_id`
 LEFT JOIN `pet_images` ON `pet_images`.`petid` = `message`.`pet_id`
 LEFT JOIN `lostpets` ON `lostpets`.`petid` = `message`.`pet_id`

错误:

 #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM `message` WHERE `message`.`status` = 'not seen') as unread FROM `m' at line 1

请帮我查一下这个查询中的错误?以及如何解决此错误?

1 个答案:

答案 0 :(得分:0)

不确定您的意图,但是对于错误,您希望在子查询中应用count函数:

select message.id as message_id,
    pet_info.id as pet_id,
    pet_info.pet_hidenum as hidenum,
    lostpets.pet_lost_date as pet_lost_date,
    lostpets.type as status,
    pet_images.img as img,
    (
        select COUNT(*)
        from message
        where message.status = 'not seen'
        ) as unread
from message
left join pet_info on pet_info.id = message.pet_id
left join pet_images on pet_images.petid = message.pet_id
left join lostpets on lostpets.petid = message.pet_id

同时尝试不使用反引号来使用标准别名和标识符名称,因为反引号会妨碍可读性。

如果这不是您想要的,请编辑您的问题并添加样本数据和预期输出。