请教多表关联查询

大家好,我想写一个sql实现逻辑如下请帮忙执教~

user用户表有username,userid字段
app应用字典表有appname,appcode(相当于id),valid(是否有效),fee(是否免费),regurl(注册url),indexurl(首页)等字段
userapp用户应用使用表userid,appcode,valid(生效)等字段

对于免费的应用,任何用户都可以用,对于收费的应用,用户必须有权限才能使用,也就是说必须在用户应用表里有对应记录,在userapp里用户和应用是一对多的关系.

现在我想把用户所有可以使用的应用和不可以使用的应用都查出来,如果是可以使用的,记录最后一条加上一个1,如果是不可以使用的,记录最后一条加上一个0,请问这条sql该怎么写?非常感谢!!

select

app.*,

case
when free = true then 1
when (select count(*) from userapp where app.appocde = userapp.appcode and userapp.userid=?) > 0 then 1
else 0 end
from app

思路就是

  1. user和app先乘下,求他们的笛卡尔集。
  2. left join表userapp,检查是否存在记录。

代码如下:(未测试)
[code="sql"]
SELECT
ua.*,
(
CASE
WHEN userapp.userid IS NULL THEN 1
ELSE 0
END) AS usable '你要的字段'
FROM
(
SELECT
*
FROM
USER,
app
)
ua ' user和app的笛卡尔集。'
LEFT JOIN userapp
ON
ua.userid =userapp.userid
AND ua.appcode=userapp.appcode
[/code]

所有免费的,加上用户和收费的笛卡尔,和userapp左连接,有记录最后字段为1,无记录为0
[code="java"]
select user.*,app.*,1 from app,user where app.free is true union
select user.*,app.*,if(userapp.userId is null,0,1) from app join user left join userapp on user.userId = userapp.userId and app.appCode = userapp.appCode where app.free is false ;[/code]

如果要限制用户,[code="java"]
select user.*,app.*,1 from app,user where app.free is true and user.userId=1 union
select user.*,app.*,if(userapp.userId is null,0,1) from app join user left join userapp on user.userId = userapp.userId and app.appCode = userapp.appCode where app.free is false and user.userId = 1;
[/code]