如何创建两个子查询MySQL
?高效和优化。
当前代码向我抛出#1241 - Operando debe tener 1 columna(s)
了phpMyAdmin的错误。
- 第一个子查询计算可用类的总数。
- 第二个子查询我想计算平均投票数和总投票数。
我的代码:
$sql = "SELECT video.title,video.icon,video.duration,video.url,video.author,level.level,
(
SELECT COUNT(*)
FROM `lessons`
WHERE video.ident_video = lessons.ident_video
),
(
SELECT AVG(vote) AS avg_vote, COUNT(*) votos
FROM `coments`
WHERE video.ident_video = coments.ident_video
)
FROM `video`
LEFT JOIN `level` on video.ident_level = level.ident_level
WHERE video.ident_state=? ORDER BY video.ident_video DESC LIMIT 5";
错误:错误 #1241 - 操作数必须有 1 列
表SQL
:
CREATE TABLE `level` (
`ident_level` smallint(3) unsigned not null auto_increment primary key,
`level` varchar(15) not null
)engine=InnoDB default charset=utf8 collate=utf8_spanish_ci;
CREATE TABLE `state` (
`ident_state` smallint(3) unsigned not null auto_increment primary key,
`state` varchar(15) not null
)engine=InnoDB default charset=utf8 collate=utf8_spanish_ci;
CREATE TABLE `video` (
`ident_video` int(11) unsigned not null auto_increment primary key,
`title` varchar(255) not null,
`icon` varchar(100) not null,
`duration` varchar(10) not null,
`url` varchar(100) not null unique,
`author` text not null,
`ident_level` smallint(3) unsigned not null,
`ident_state` smallint(3) unsigned not null,
foreign key(`ident_level`) references `level`(`ident_level`)
on delete cascade on update cascade,
foreign key(`ident_state`) references `state`(`ident_state`)
on delete cascade on update cascade
)engine=InnoDB default charset=utf8 collate=utf8_spanish_ci;
CREATE TABLE `lessons` (
`ident_lesson` smallint(11) unsigned not null auto_increment primary key,
`page` int(11) unsigned not null,
`title` varchar(100) not null,
`url` varchar(100) not null unique,
`status` smallint(1) not null,
`ident_video` int(11) unsigned not null,
foreign key (`ident_video`) references `video`(`ident_video`)
on delete cascade on update cascade
)engine=InnoDB default charset=utf8 collate=utf8_spanish_ci;
CREATE TABLE coments(
`ident_coment` smallint(11) unsigned not null auto_increment primary key,
`title` varchar(255) not null,
`coment` text not null,
`vote` float(3) not null,
`ident_video` int(11) unsigned not null,
`ident_user` int(11) unsigned not null,
`status` smallint(1) unsigned not null,
foreign key (`ident_video`) references `video`(`ident_video`)
on delete cascade on update cascade,
foreign key(`ident_user`) references `user`(`ident_user`)
on delete cascade on update cascade
)engine=InnoDB default charset=utf8 collate=utf8_spanish_ci;
Bulten 我试图重现您的数据。
您可以尝试
JOIN
在子查询中使用,这样您就可以使用您在里面选择的列。它看起来或多或少像这样(为简单起见,我删除了一些列):
概念证明
VER DEMO EN REXTESTER
结果