SQL 子查询匹配硬编码的 IN 条件,但不匹配子查询
我有一群人参加了测试。我可以使用此查询选择他们的 ID:
SELECT person_id
FROM tests
WHERE test_code = 1234
我想从人口统计表中提取这些人的记录,因此我尝试使用此子查询来执行此操作:
SELECT *
FROM demographics d
WHERE d.person_id IN (
SELECT t.person_id
FROM tests t
WHERE t.test_code = 1234
)
...但我没有得到任何结果。如果我从(功能)子查询中获取几个 ID 并将它们硬编码到 IN 条件中:
SELECT *
FROM demographics d
WHERE d.person_id IN (01123, 58132)
...查询有效。我必须在这里遗漏一些非常基本的东西 - 你知道它是什么吗?
可能的复杂因素:t.person_id 是 char13,d.person_id 是 varchar50。这是 MS SQL Server 9.0.4035;我在 SQL Server Management Studio 工作。
I have a group of people who have taken a test. I can select their IDs with this query:
SELECT person_id
FROM tests
WHERE test_code = 1234
I'd like to pull these individuals' records from a demographics table, so I tried this subquery to do so:
SELECT *
FROM demographics d
WHERE d.person_id IN (
SELECT t.person_id
FROM tests t
WHERE t.test_code = 1234
)
... but I'm not getting any results. If I take a couple of the IDs from the (functional) subquery and hard-code them into the IN criteria:
SELECT *
FROM demographics d
WHERE d.person_id IN (01123, 58132)
... the query works. I've got to be missing something really fundamental here - do you know what it is?
Possible complicating factors: t.person_id is char13, d.person_id is varchar50. This is MS SQL Server 9.0.4035; I'm working in SQL Server Management Studio.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,您没有正确地混淆测试。应该是:
其次,如果 t.person_id 返回任何 NULL,您将不会得到任何结果。
First off, you are not aliasing tests properly. Should be:
Secondly, if t.person_id returns any NULLs you will not get any results.
问题可能是 TESTS.PERSON_ID 带有尾随空白,因为它被声明为 CHAR 而不是 VARCHAR。我不确定如何删除 SQL Server 中的尾随空白(自从我使用它以来已经有一段时间了),但在 Oracle 中我会使用 TRUNC 函数,如
编辑中所示:我相信 SQL Server 中的等效函数是 RTRIM。
The problem may be that TESTS.PERSON_ID is coming in with trailing blanks on it since it's declared as CHAR instead of VARCHAR. I'm not sure how to remove trailing blanks in SQL Server (it's been a while since I used it), but in Oracle I'd use the TRUNC function, as in
Edit: I believe the equivalent function in SQL Server is RTRIM.
你试过没有t吗?在子查询中?看看你的原始子查询,你没有给表测试一个别名 t ...
Have you tried it without the t. in the subquery? as looking at your original subquery your not giving the table tests an alias of t...
我从未在 IN 子句中尝试过子查询,所以我不能保证这有效,但尝试一下:
我只是在子查询周围添加了括号,这是常见的做法。再说一遍,我从未在 IN 子句中尝试过 subq,因此不能保证它有效,但值得一试。
I've never tried a subquery in an IN clause, so I can't guarantee this works, but try this:
I simply added parentheses around your subquery, which is common practice. Again, I've never tried a subq in an IN clause so can't guarantee this works but it's worth a shot.