mysql 怎样一条语句查询出数据和数量

有两张表
课单表: t_book 字段: id userId
课件表: t_lesson 字段: bookId
t_lesson.bookId 关联了 t_book.id

现在的方法是分开两条SQL查询
查询用户课单: select * from t_book where userId = 2
查询课件数量: select count(*) from t_lesson where bookId = 1
请问如何合并成一条SQL?

可以这样:

select count(*)
from t_lesson
where t_lesson.bookId in (
    select id 
    from t_book 
    where t_book.userId=2);

望采纳,谢谢

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-06-05
第一个查询返回的结果只有一行记录吗?试试这个吧:
select t1.*,t2.num from (select * from t_book where userId = 2) t1
full join (select count(*) as num from t_lesson where bookId = 1) t2
on 1=1
第2个回答  2018-06-05
在查询结果中查询>=9的个数select COUNT(id),(select COUNT(id) from t where time>=9) from t