你能为我重写这个吗?左连接表和子查询

发布于 2024-11-03 04:42:53 字数 441 浏览 4 评论 0原文

CREATE TABLE TR(STUDENT_ID int, SUBJECT_ID int, grade int);
INSERT INTO tr SELECT * FROM results where results.STUDENT_ID=3;
SELECT * FROM subjects LEFT JOIN tr ON subjects.SUBJECT_ID=tr.SUBJECT_ID;
DROP TABLE TR;

是否可以将上述重写为一个查询?我在网上找遍了,还是做不到。我正在使用德比数据库。

我的想法是,我想将具有一定行数的表主题与表结果中的匹配结果(如果有针对特定学生的任何结果)连接起来。如果没有结果,我希望输出行仅包含来自表主题的数据。因此,输出行数将始终等于主题中的行数。

上面的代码运行良好,但它给我的程序带来了麻烦,因为必须创建一个表。我想避免这种情况。

CREATE TABLE TR(STUDENT_ID int, SUBJECT_ID int, grade int);
INSERT INTO tr SELECT * FROM results where results.STUDENT_ID=3;
SELECT * FROM subjects LEFT JOIN tr ON subjects.SUBJECT_ID=tr.SUBJECT_ID;
DROP TABLE TR;

Is it possible to rewrite the above as one query? I've searched all over the net and still can't do it. I'm using derby database.

The idea is that I want to join table subjects, which has a certain number of rows, with matching results from table results, if there are any for a specific student. If there are no results, I want the ouput rows to contain only data from table subjects. So, the number of output rows will always equal the number of rows in subjects.

The above code works well, but it gives me trouble in my program, because a table has to be created. I would like to avoid that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

思慕 2024-11-10 04:42:53
SELECT *
FROM subjects s
LEFT JOIN (
    SELECT * FROM
    results r
    WHERE r.STUDENT_ID = 3
) x ON s.SUBJECT_ID = x.SUBJECT_ID
SELECT *
FROM subjects s
LEFT JOIN (
    SELECT * FROM
    results r
    WHERE r.STUDENT_ID = 3
) x ON s.SUBJECT_ID = x.SUBJECT_ID
安静被遗忘 2024-11-10 04:42:53

根据上面给出的示例查询,它可以重写,因为

SELECT subjects.* FROM 
subjects LEFT JOIN results 
ON subjects.SUBJECT_ID = results.SUBJECT_ID
WHERE results.STUDENT_ID = 3;

我没有使用过 derby。但我认为,这应该有效。

Based on the example query given above, it can be rewritten as

SELECT subjects.* FROM 
subjects LEFT JOIN results 
ON subjects.SUBJECT_ID = results.SUBJECT_ID
WHERE results.STUDENT_ID = 3;

I haven't worked with derby. But I think, this should work.

清风夜微凉 2024-11-10 04:42:53

SELECT * FROM subject LEFT JOIN results ON subject.SUBJECT_ID=results.SUBJECT_ID AND results.STUDENT_ID=3;

SELECT * FROM subjects LEFT JOIN results ON subjects.SUBJECT_ID=results.SUBJECT_ID AND results.STUDENT_ID=3;

冰葑 2024-11-10 04:42:53

这应该相当于

SELECT * FROM subjects
LEFT JOIN results ON results.SUBJECT_ID = subjects.SUBJECT_ID AND results.STUDENT_ID = 3;

假设您在某个特定学生的结果中最多有一个条目。

That should be equivalent to

SELECT * FROM subjects
LEFT JOIN results ON results.SUBJECT_ID = subjects.SUBJECT_ID AND results.STUDENT_ID = 3;

Assuming you have at most one entry in results for a specific student.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文