在SQL的子查询中使用limit-clause和parent-query-column

时间:2013-07-16 14:20:10

标签: mysql join sql-limit

我想在子查询中使用limit子句。同时,父查询列应该可以在子查询中访问。我正在使用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不支持以下内容(LIM / 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 query

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

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;

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 Fiddle