Mysql 选择不存在的内容
我有这张桌子。我想重新选择不存在的项目,以便创建它们 table tags +---------+-------+ | tagId | name | | 1 | C | | 2 | DX | | 3 | CG | 假设SQL看起来像: select name from tags where name in ( 'C', 'CG', 'RX' ) 你得到了“C”和“CG”,所以你知道你必须创建“RX” 当“RX”不存在时,有没有办法让类似这样的MySQL语句返回“RX”?当然 唯一的问题是,如果not in列表很长,这个查询会很慢,因为它必须根据每行的“name”字段检查每个元素,以确定它是否不在列表中,而不是in,当它匹配时,它将在该点停止检查列表并返回该行。 编辑:上述解决方案是错误的。我很抱歉。真正的解决办法如下 以下是如何在SQL的一行中实现这一点:Mysql 选择不存在的内容,mysql,select,Mysql,Select,我有这张桌子。我想重新选择不存在的项目,以便创建它们 table tags +---------+-------+ | tagId | name | | 1 | C | | 2 | DX | | 3 | CG | 假设SQL看起来像: select name from tags where name in ( 'C', 'CG', 'RX' ) 你得到了“C”和“CG”,所以你知道你必须创建“RX” 当“RX”不存在时,有没有办法让类
select name from (
select "C" as name
union select "CG"
union select "RX"
) as foo
where name not in (select name from tags);
当然
唯一的问题是,如果not in列表很长,这个查询会很慢,因为它必须根据每行的“name”字段检查每个元素,以确定它是否不在列表中,而不是in,当它匹配时,它将在该点停止检查列表并返回该行。
编辑:上述解决方案是错误的。我很抱歉。真正的解决办法如下
以下是如何在SQL的一行中实现这一点:
select name from (
select "C" as name
union select "CG"
union select "RX"
) as foo
where name not in (select name from tags);
假设您的标记“c”、“cg”和“rx”位于一个名为tags_match的表中,其结构与上面相同 然后你可以这样做:
select tr.name
from tags as tl
right join tags_match as tr
on tl.name = tr.name
where tl.name is null
这将找到标签中所有不在标签中的匹配项,因此这将为您提供所需的结果,但不幸的是,您的标签“c”、“cg”和“rx”不在表中:
不管怎样,我们都可以使用子查询来“伪造”表
select tr.name
from tags as tl
right join (select 'cg' as name
union select 'c' as name
union select 'rx' as name) as tr
on tl.name = tr.name
where tl.name is null
虽然有点难看,但这会奏效的。如果你有很多要测试的项目,你可能想考虑创建一个真正的临时表。
让我们假设你的标签“C”、“CG”、“RX”都在一个名为TaysSub匹配的表中,其结构与上面的
相同。 然后你可以这样做:select tr.name
from tags as tl
right join tags_match as tr
on tl.name = tr.name
where tl.name is null
这将找到标签中所有不在标签中的匹配项,因此这将为您提供所需的结果,但不幸的是,您的标签“c”、“cg”和“rx”不在表中:
不管怎样,我们都可以使用子查询来“伪造”表
select tr.name
from tags as tl
right join (select 'cg' as name
union select 'c' as name
union select 'rx' as name) as tr
on tl.name = tr.name
where tl.name is null
虽然有点难看,但这会奏效的。如果您有很多要测试的项目,您可能想考虑创建一个真正的临时表。是在任何其他表中找到的“RX”之类的项目,还是您只需要检查一些外部项目列表?或者您只是要检查一些外部项目列表?这将返回名称不在列表中的行。海报似乎要返回列表中名称不在表中的一组新行。这将返回列表中名称不在的行。海报似乎想要返回列表中名称不在表中的一组新行。+1非常好-我忘记了使用UNION创建行,而专注于另一个表中存在的“名称”。+1非常好-我忘记了使用UNION创建行,而专注于另一个表中存在的“名称”。