我是SQL的初学者。我正在使用查询数据库的程序,然后处理结果。默认查询为:
SELECT *
FROM data,
questions,
users
where users.U_Id = data.Subj_Id
and data.Subj_Id between 1 and 10
and data.Q_Id = questions.Q_Id
and questions.Q_Id between 1 and 10
order by Subj_Id;
我希望查询每个Subj_Id
和每个Q_Id
。我不知道有多少,不同的主题有不同的问题。我该如何改变上述问题?
答案 0 :(得分:4)
您可以像这样重写上述查询。
select *
from
data
inner join
users on users.U_Id = data.Subj_Id
inner join
questions on data.Q_Id = questions.Q_Id
where data.Subj_Id between 1 and 10
and questions.Q_Id between 1 and 10
order by Subj_Id;
通过将表之间的连接与数据上的过滤器分开,可以更清楚地实现。
因此,要查询整个数据库,只需从上面删除where
子句......
select *
from
data
inner join
users on users.U_Id = data.Subj_Id
inner join
questions on data.Q_Id = questions.Q_Id
order by Subj_Id;