将 IN 与子查询一起使用
我有两个表,其中一个表有一列保存另一个表的 ID。这一列可以容纳多个 ID,因此我将其存储为一个列表,例如“1,2,3,4”可以是值。所以我尝试使用以下内容:
SELECT TableAValue
FROM TableA
WHERE TableAID IN
(SELECT TableAID FROM TableB WHERE TableBID = 1)
这只会带回一个值。
现在,如果我使用:
SELECT TableAID FROM TableB WHERE TableBID = 1
这会返回四个值。另外,如果我复制这四个值并使用:
SELECT TableAValue
FROM TableA
WHERE TableAID IN
(1,2,3,4)
这将带回我想要的四个值。这似乎是一件非常简单的事情,所以我想我要么做得完全错误,要么遗漏了一些小细节。有什么想法吗?
I have two tables, in one the tables there is a column that holds the ID of the other table. This column could hold more than one ID so I am storing it as a list so for instance "1,2,3,4" could be the values. So I try to use the following:
SELECT TableAValue
FROM TableA
WHERE TableAID IN
(SELECT TableAID FROM TableB WHERE TableBID = 1)
This only brings back one value.
Now if I use:
SELECT TableAID FROM TableB WHERE TableBID = 1
This brings back four values. Also if I copy those four values and use:
SELECT TableAValue
FROM TableA
WHERE TableAID IN
(1,2,3,4)
This will bring back the four values I am after. This seems like something very simple to do, so I guess I'm either doing it completely wrong or I'm missing some small detail. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如评论讨论中提到的,您的错误是在单个字段中保存四个值。这样做意味着您保存的是一个字符串、单个值,而不是整数列表。如果要保存多个值,则需要多个位置来单独保存它们。
因此,如果您有四个记录,每个记录在 TableAID 中都有不同的值,那么它将完全按照您的预期工作。
As mentioned in the comments discussion, your mistake is to hold four values in a single field. Doing so means that you're holding a string, a single value, not a list of integers. If you want to hold several values, you need several places to hold them individually.
So, if instead you have four records, each with a different value in TableAID, it will work exactly as you expect.