我的asp.net网站上有一个Linq To Sql查询。
此查询也有效慢,并且我确信它可以改进。
任何人都可以帮我改写此查询吗?
我认为使用“加入”可以更快,但无法正确使用它。 :(
以下是查询:(输入参数:INT_GENDER)
var users = from u in db.Users
where (u.gender == INT_GENDER) && (u.age > 25)
let fileId = (from f in db.Files
where f.username == u.username && f.approved
orderby f.primary
select f.id).FirstOrDefault()
let answer = (from a in db.Answers
where (a.username == u.username) &&
(a.q_id == (from q in db.Questions where q.type == 1
select q.id).FirstOrDefault()) &&
a.approved
select a).FirstOrDefault()
select new {
Username = u.u_username,
FileId = fileId !=null ? fileId : GetEmptyFileId(),
Answer = (answer == null ? "" : (answer.approved ? answer.value: "Empty"))
};
查询基于3个表。 表格: 1.用户 2.文件 3.答案
谢谢! 丹
答案 0 :(得分:0)
这是我在普通T-SQL中解密此问题的适度尝试。希望这会有所帮助。
SELECT u.username, f.id, a.value, a.approved
FROM users AS u
JOIN files AS f ON u.username = f.username
JOIN answers AS a ON a.username = u.username
JOIN questions AS q ON a.q_id = q.id
WHERE u.gender = @INT_GENDER
AND u.age > 25
AND f.approved = 1
AND a.approved = 1
AND q.type = 1