简体   繁体   English

如何有效地检查记录是否存在于mysql表中?

[英]How to efficiently check if record exists in mysql table?

I'm coding PHP kohana application and in one part of it I need to insert a few records into table. 我正在编写PHP kohana应用程序的代码,在其中的一部分中,我需要在表中插入一些记录。

My table structure: 我的表结构:

TABLE BOOKINGS
id int
booked_object_id int
date_from date
date_tom date

This table has about 10k records with booked objects. 该表大约有1万条包含已预订对象的记录。

Now in one of my PHP function I have array with new data, which I want to insert into this table. 现在,在我的PHP函数之一中,我有了一个包含新数据的数组,我想将其插入此表中。 There are about 20-30 new bookings to insert when my function is executed. 执行我的功能时,大约需要插入20-30个新的预订。

Now let's get to my main problem - I want it to check if ANY of bookings which I want to insert into table is already booked (object_id and date_from is the same as in my php array). 现在让我们解决我的主要问题-我希望它检查是否要预订要插入表中的任何预订(object_id和date_from与我的php数组中的相同)。 If any of it is already booked, my function will not insert anything new into table. 如果其中任何一个已被预订,我的函数将不会在表中插入任何新内容。

Is there a more efficient way than getting all contents of mysql table into PHP array and check it 20 times (or number of my inserts)? 有没有比将mysql表的所有内容放入PHP数组并检查20次(或插入次数)更有效的方法?

If you are planning on looking up a certain column in your table then you should index it. 如果打算在表中查找某个列,则应为其建立索引。 This will create a hashtable that the db-server will use to lookup rows. 这将创建一个哈希表,数据库服务器将使用该哈希表查找行。

And as for the efficiency of making 20 calls.. you could use an IN statement to select all existing records in 1 call and simply ignore the already existing ones when inserting. 至于提高20个调用的效率,您可以使用IN语句在1个调用中选择所有现有记录,而在插入时仅忽略已存在的记录。

reference: 参考:

expr IN (value,...) expr IN(值,...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM