MySQL - 检查行是否存在

4

我希望只有在另一个表中存在该行的父级时才插入一行。

thread1表

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

线程2 表格

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');

由于3thread2表中不存在,因此它应该失败。

可以通过从线程表中进行检查来实现。但是,是否可以在不进行额外查询的情况下实现?

更新

上面的表已经更新了。 thread_type指的是thread1thread2表。


在插入时,您是否可以知道线程类型? - Milan Gupta
1
你应该考虑只使用一个线程表,并在该表中添加一个“线程类型”的字段。 - deed02392
3个回答

3

在两个表之间创建一个外键,使用thread(id)作为父表,comment(thread_id)作为子表,这样做就可以了。

你需要运行以下命令 -

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

你能举个多重继承的例子吗?我不太理解这种情况。 - Yaron Idan
1
无法为两个不同的表创建一个外键。使用一个引用两个表的表似乎也是不好的设计。如果您要为您的主题创建两个表,那么您应该为您的评论创建两个表。 - Yaron Idan
这也超出了你最初问题的范围,既然你已经得到了当前问题的答案 - 我会感激如果你能接受我的答案。 - Yaron Idan

1
尝试一下:

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

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

0

这可能会做到这一点:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接