select语句中的子查询返回sql错误

6mw9ycah  于 2021-06-18  发布在  Mysql
关注(0)|答案(4)|浏览(414)

我得到了这个查询的sql错误
错误号:1064
sql语法有错误;查看与您的mysql服务器版本对应的手册,以获取在“*”附近使用的正确语法
cast\ U galleryq
加入'all\u media`r on q.all\u media\u id=r.id
其中1号线的q.pa'

SELECT `cast_name`, `cast_slug`, (SELECT count(q.*)
 FROM `cast_gallery` q
 JOIN `all_media` r on q.all_media_id=r.id
 WHERE q.parent = `casts`.`id` AND r.approved=1) as image_gallery, `active`, `view`, `checked`, `sex`, `id`
FROM (`casts`)
ORDER BY `cast_name` asc
LIMIT 10

如何解决?

dddzy1tm

dddzy1tm1#

您可以尝试使用q.all\u media\u id代替count(q.*)

SELECT `cast_name`, `cast_slug`, (SELECT count(q.all_media_id)
 FROM `cast_gallery` q
 JOIN `all_media` r on q.all_media_id=r.id
 WHERE q.parent = `casts`.`id` AND r.approved=1) as image_gallery, `active`, `view`, `checked`, `sex`, `id`
FROM (`casts`)
ORDER BY `cast_name` asc
LIMIT 10
i7uq4tfw

i7uq4tfw2#

count的语法不正确。如果我们想找出子查询中的行数,我们可以使用count(*)。请参阅http://www-db.deis.unibo.it/courses/tw/docs/w3schools/sql/sql_func_count.asp.html 更多澄清。

SELECT `cast_name`, `cast_slug`, (SELECT count(*)
FROM `cast_gallery` q
JOIN `all_media` r on q.all_media_id=r.id
WHERE q.parent = `casts`.`id` AND r.approved=1) as image_gallery, `active`, 
`view`, `checked`, `sex`, `id`
FROM (`casts`)
ORDER BY `cast_name` asc
LIMIT 10

应该有用

nwnhqdif

nwnhqdif3#

为了计算总行数,我们使用 COUNT(*) ,不是 Count(q.*) . 另外,不需要括号 castsFrom 条款。

SELECT `cast_name`, 
       `cast_slug`, 
       (SELECT count(*)
        FROM `cast_gallery` q
        JOIN `all_media` r on q.all_media_id=r.id
        WHERE q.parent = `casts`.`id` AND 
              r.approved=1) as image_gallery, 
      `active`, 
      `view`, 
      `checked`, 
      `sex`, 
      `id`
FROM `casts`
ORDER BY `cast_name` asc
LIMIT 10

其他信息: COUNT(...) 用于计算非空值的数目;然而 COUNT(*) 将计算检索到的行总数,无论它们是否包含空值。

w8biq8rn

w8biq8rn4#

试着改变一下 count(q.*)count(*)

相关问题