Mysql - 检查行是不是存在

Posted

技术标签:

【中文标题】Mysql - 检查行是不是存在【英文标题】:Mysql - Check if row existsMysql - 检查行是否存在 【发布时间】:2016-12-05 15:44:30 【问题描述】:

我只想插入一行,如果它的父级存在于另一个表中。

thread1 表

id | content      | 
1  |  Hello World |
2  |  Bye World   |

thread2 表

id | content     | 
1  |  Naruto     |
2  |  DragonBallz|

评论表

id | thread_id| thread_type | content    |
1  |    1     |     thread1 |    hellow  |
2  |    1     |     thread2 |    bye-bye |

如果我这样做了

INSERT INTO comment(thread_id,thread_type,content)VALUES('3','thread2','Whatever');

它应该会失败,因为3 存在于thread2 表中。

这可以通过从线程表中检查来实现。但是没有它有可能吗?不做额外的查询?

更新

以上表格已更新。 thread_type 指的是表thread1 & thread2

【问题讨论】:

是否有可能在插入时知道thread_type? 您应该考虑为线程设置一个表,并在该表中为“thread_type”设置一个字段。 【参考方案1】:

在两个表之间创建一个外键,使用 thread(id) 作为父级,comment(thread_id) 作为子级,应该可以解决问题。

这是你应该运行的命令 -

ALTER TABLE comment
    ADD FOREIGN KEY
    (thread_id)
    REFERENCES thread (id)

【讨论】:

你能举一个多父母的例子吗?我不太明白这个场景。 没有办法为两个不同的表创建一个外键。使用一个引用两个表的表似乎也是糟糕的设计。如果你要为你的线程创建两个表,你应该为你的 cmets 创建两个表。 这也超出了您原始问题的范围,并且由于您已收到当前问题的答案 - 如果您能接受我的回答,我将不胜感激。【参考方案2】:

试试这个:

INSERT INTO comment ('3','thread2','Whatever')  
select t2.id,0,0
from thread2 t2
where t2.id = '3';  

我假设,您的评论表中的 id 是主键并自动递增。 上面的查询将根据您的线程类型从 thread2 表中选择 id。如果在 thread2 表中找到 id,它将插入一个新行,否则插入零行,因为从父表中选择了零行。

希望对你有帮助:)

【讨论】:

【参考方案3】:

这可能会:

INSERT INTO comment(thread_id,thread_type,content)
(select id as thread_id, thread_type, '[content]' as content
from ((select id,'thread1' as thread_type from thread1)
union 
(select id,'thread2' as thread_type from thread2 )) threads
where threads.id=[thread_id] and threads.thread_type ='[thread_type]')

在你的示例中

[thread_id]=3
[thread_type]=thread2
[content]=Whatever

所以如果有这样的父级,它将插入一行,否则不会插入任何内容。

【讨论】:

以上是关于Mysql - 检查行是不是存在的主要内容,如果未能解决你的问题,请参考以下文章

MySQL触发器检查行字段是不是存在

SQLAlchemy - MySQL - 检查现有表中是不是存在行[重复]

Mysql,检查行是不是存在,如果它确实获取值,如果不插入

如何检查MySQL中是不是存在一行? (即检查电子邮件是不是存在于 MySQL 中)

Flask-SQLAlchemy 检查表中是不是存在行

检查表中是不是存在行的最有效方法是啥?