求一条sql语句

数据表结构是这样子

表一(action):
id name
1  吃饭
2  说话
3  唱歌

表二(log):
id action_id status
1      1      0
2      1      1
3      1      1
4      1      1
5      2      1
5      2      1
7      2      1
8      3      0 
9      3      1

求出表一(id)对应表二中(action_id)存在数据总和,以及status=1的数量等于总和的action数据出来:
比如:
action表里的第一条id为1的数据,在log表里的记录总数为4条,但是stauts=1的记录却只有3条,那么过滤掉不取;
然后我们来看action表里第二条id为2的数据,在log表里的记录总数为3status为1的记录也有3条,那么就把action表里id为2的数据取出来,依次类推...

  1. 求一条sql语句或者能做到这样效果的方法

  2. 可以实现分页效果,每次取出n条action表满足条件的数据

阅读 2.5k
3 个回答

SELECT id,name FROM action WHERE NOT EXISTS (SELECT * FROM log WHERE action.id=log.action_id and log.stauts=0) and id =1 limit 0,10

这是取一条的,分页就是加上limit后面的值,你需要自己算,假如取所有id的你把id=1去掉就行了!

简单解释下:
你的需求是需要 log里有记录且无stauts=0的,其实你的需求是可以这样想的

sql的意思 就是 取log表里 该id没有stauts=0的action!

本需求的关键就在于log表里有stauts=0的不取该action,那排除他就好了!

具体是要了解NOT EXISTS 和 exists的用法
http://www.cnblogs.com/mytech...

select * from action where id not in (select action_id from log where status=0) limit 0,2;

select a.* from action a , log l where a.id=l.action_id and l.status=1 limit 0, 10

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题