1

我想在子查询中使用限制子句。同时,父查询列应该可以在子查询中访问。我正在使用 MySQL 并想做如下的事情:

select * from users u1 join (SELECT b1.userid from bids b1 where b1.userid=u1.userid limit 0,4) a1

当然这是无效的,因为 b1.authorid 不能以这种方式访问​​。

1)我想在应用 where 子句后限制结果,因此明确以下被排除:

select * from users u1 JOIN (SELECT b1.userid from bids b1 limit 0,4) a1 ON b1.userid=u1.userid

2) MySQL 不支持以下操作 ( LIMIT with IN/ANY/EVERY/SOME ):

select * from users u1 join bids b2 ON b2.userid IN (SELECT b1.userid from bids b1 where b1.userid=u1.userid limit 0,4)

有没有办法在 MySQL 中实现预期的结果?

SQLFiddle 链接: SQL 查询

让我以不同的方式表达查询的含义。假设 ANS 是输出,USER 是 users 表,BID 是 bids 表。查询的表示将是这样的:

USER=table(users);
While(USER has next raw) {
  uraw=USER.nextraw;
  BID=table(bids);
  count=0;
  While(BID has next raw) {
    braw=BID.nextraw;
    if(uraw.author < braw.id) {
      if(count>=0) {
        ANS.add(fields from uraw,fields from braw);
      }
      count=count+1;
    }
    if(count>=4) {
      break;
    }
  }
}
return ANS;
4

2 回答 2

0

是的,它支持连接查询中的限制。只需将 ON ON b1.authorid = a1.id 更改为 b1.authorid = a1.id

SELECT * FROM books b1 JOIN (SELECT * FROM authors LIMIT 0,4) a1 where b1.authorid = a1.id
于 2013-07-16T14:29:24.400 回答
0

鉴于您的 SQL 小提琴,这样的事情应该可以工作:

 SELECT u.*
      , i.*
      , x.bid
      , x.bid_date
   FROM bids x 
   JOIN bids y 
     ON y.userid = x.userid 
    AND y.bid_date <= x.bid_date 
   JOIN users u
     ON u.userid = x.userid
   JOIN items i
     ON i.itemno = x.itemno
  GROUP 
     BY userid,bid_date
 HAVING COUNT(*) <= 4;

SQL 小提琴

于 2013-07-16T21:11:54.073 回答