Mysql - 检查行是否存在

时间:2016-07-31 12:28:26

标签: php mysql sql insert duplicates

我想只在父的另一个表存在的情况下插入一行。

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表中没有<{1}}

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

更新

上面的表已更新。 thread2引用表格thread_type&amp; thread1

3 个答案:

答案 0 :(得分:3)

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

这是你应该运行的命令 -

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

答案 1 :(得分:1)

试试这个:

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

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

希望有所帮助:)

答案 2 :(得分: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

因此,如果有这样的父母,则会插入一行,否则不会插入任何内容。

相关问题