Home  >  Article  >  Backend Development  >  求mysql语句(insert之前先查询)

求mysql语句(insert之前先查询)

WBOY
WBOYOriginal
2016-06-06 20:15:551270browse

数据表如下:

id    parent    a      b    others
---------------------------------------
1        0      7      8
---------------------------------------
2        1      8      7
---------------------------------------
3        1      7      8
---------------------------------------
4        1      8      7
---------------------------------------

比如:现在已知a=7、b=8,但不知道parent的值,插入之前要查询数据表中已存在a=7 && b=8的,或者a=8 && b=7的那条记录的parent的值(保证数据表中满足a=7 && b=8,或者a=8 && b=7的那些记录的parent都是同一个值)。
请问如何写sql?先select后insert?一条语句能搞定么

回复内容:

数据表如下:

id    parent    a      b    others
---------------------------------------
1        0      7      8
---------------------------------------
2        1      8      7
---------------------------------------
3        1      7      8
---------------------------------------
4        1      8      7
---------------------------------------

比如:现在已知a=7、b=8,但不知道parent的值,插入之前要查询数据表中已存在a=7 && b=8的,或者a=8 && b=7的那条记录的parent的值(保证数据表中满足a=7 && b=8,或者a=8 && b=7的那些记录的parent都是同一个值)。
请问如何写sql?先select后insert?一条语句能搞定么

@Eapen 参考我对你的回答的评论。
@xaero 我觉得你的问题把我们都带偏了。
对于消息的首发来说是不存在parent这个属性的,因为消息是按照时间顺序排列的。只有论坛的帖子回复才有parent的问题,这个parent可以在前台显示的时候使用,可以把相关的讨论集中起来便于阅读,因为这种结构打破了发帖时间的规律,所以才需要额外的指定parent。
明显消息不存在这个问题,就算你的消息是针对某个话题产生的,那也应该是reference_id而不是parent。

你们觉得呢?

我理解你的意思了。这可以通过另一个表去维护。
table message_groups
group_id users
1 7,8 //信息交流者,按照用户id从小到大排列,用逗号分隔
2 7,9
...
table messages
group_id from_user to_user message time
1 7 8 Test1 ....
1 8 7 Re: Test1 ....

这样你觉得有帮助吗?

IF EXISTS (SELECT * FROM Table_Name WHERE (a='7' and b='8') OR (a='8' and b='7'))
BEGIN
    --EXIST
END
ELSE
BEGIN
    INSERT INTO Table_Name(Column,...) VALUES('')
END

有点没懂 为什么不知道parent的值?在读取列表的时候就应该知道id的值了呀写入的时候直接带上就行

oschina的私信功能就是这样的,明明是已经存在的一对用户会话,我不“回复”,点“新发送”,也会归纳为原先的会话。。。不知道是怎么实现的。。。。oschina上都是无关痛痒的聊天,没人答

你可以写存储过程的,可以完美解决你的问题。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn