且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MYSQL:我可以在子查询中使用外部查询表别名

更新时间:2023-02-26 10:02:43


我想做什么?想象一下,Table1有10个学生姓名,
现在有Table2,其中每个学生
中有10条记录(行)。如果我尝试在两个表上使用join,它将返回
100个记录(每个学生10个记录)。我想要的是,限制
结果返回的结果,每个学生5条记录所以,我应该得到5
记录每个学生,因此50输出行

What I am trying do? Imagine there is Table1 with 10 student names, now there is Table2 which has 10 records(rows) for each of the student present in table1. If I try to use join on both tables, it will return 100 records(10 records for each student). What I want is, to limit the result returned by join by 5 records per students So, I should get 5 records per student hence 50 output rows

回答: -
Table1(studentid,.......)
Table2(id,........., studentid)

Answer for this:- Table1(studentid,.......) Table2(id,.........,studentid)

select s.*,temp.* from (SELECT @var:=if(@var2= a.studentid,@var+1,1) sno, @var2:= studentid, a.*
FROM Table2 a,(select @var:=0) b, (select @var2:=0) c 
order by studentid) temp, Table1 s where temp.sno<=5;




对于您的表结构: - 表结构(资产):ID | TypeID |
CategoryID |价值| isActive |创建日期|到期日期|
AssetOwner表结构(用户活动):| ID | ActivityTypeID |
UserID |时间| onAssetID | CommentID

For your table structures:- Table Structure(asset): ID | TypeID | CategoryID | Worth | isActive | CreationDate | ExpiryDate Value | AssetOwner Table Structure(useractivity): | ID | ActivityTypeID | UserID | Time | onAssetID | CommentID



select s.*,temp.* 
from 
     (SELECT @var:=if(@var2= a.onAssetID,@var+1,1) sno, @var2:= onAssetID, a.*
      FROM useractivity a,(select @var:=0) b, (select @var2:=0) c 
      order by onAssetID) temp, asset s 
where temp.sno<=5;