MySQL,给定一个列表,从表中选择丢失的行
在过去的几分钟里,这让我发疯,
我有一个表,假设 table_alphabet 有三列。
letter(pri) col1 col2
a 24 55
b 45 45
c 23 44
...
y 33 55
z 45 22
现在,在我的应用程序中,我有一个列表('a'、'b'、'lol'、'cats'、'z'、'foo')。
如果我这样做,
SELECT letter FROM table_alphabet WHERE letter IN ('a', 'b', 'lol', 'cats', 'z', 'foo')
我只会得到行,(a,b,z),
但我想要的是得到“lol”,“cats”,“foo”。 或者用英语来说,表格中缺少我列表中的哪些项目。
任何帮助将不胜感激,我今天似乎大脑出现故障。
This has been driving me crazy for the past few minutes
I have a table, lets say table_alphabet with three columns.
letter(pri) col1 col2
a 24 55
b 45 45
c 23 44
...
y 33 55
z 45 22
Now in my application I have a list ('a', 'b', 'lol', 'cats', 'z', 'foo').
If I do
SELECT letter FROM table_alphabet WHERE letter IN ('a', 'b', 'lol', 'cats', 'z', 'foo')
I only get the rows, (a, b,z)
What I want though is to get 'lol', 'cats', 'foo'. Or in english, what items in my list are missing from the table.
Any help would be appreciated, I seem to be having a brain malfunction today.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
抱歉,我第一次完全误解了这个问题。 您将需要一个子查询来将列表中的所有字母提取为行。 我能想到的唯一方法是将它们全部联合起来:
所以换句话说,您的应用程序需要采用列表“
('a', 'b', 'lol', 'cats', 'z', 'foo')
" 并将其重写为 UNION:...并将其插入到查询中。 这应该返回列表中不存在于 table_alphabet 表的字母列中的字母:
Sorry, I completely misread the question the first time through. You will need a subquery that can pull all of the letters in your list as rows. The only way I can think of doing this is by UNIONing them all together:
So in other words, your application will need to take the list "
('a', 'b', 'lol', 'cats', 'z', 'foo')
" and rewrite it in a UNION:...and insert that into the query. This should return the letters from the list that are NOT present in the letter column of the table_alphabet table:
我可能完全没有根据,但我认为仅靠 SQL 无法实现这一目标。
现在,如果您将列表加载到表中,将其命名为 table_list,然后将其左连接到 table_alphabet 并排除 Alphabet 为空的所有行,那么您可以获得排除列表。
I may be completely off base, but I dont think you are going to achieve that in just SQL alone.
Now, if you loaded your list into a table, call it table_list, then left join it to your table_alphabet and exclude all rows where alphabet is null then you could get your list of exclusions.
即使您正在过滤的非静态列表,NOT IN 命令也将起作用。 您可以使用子查询,例如:
The NOT IN command will work even with a non static list you are filtering against. You can use a sub-query like: