简体   繁体   English

如果ID不存在,则在表2上执行MySQL UPDATE表1和INSERT

[英]MySQL UPDATE table 1 and INSERT on table2 if id doesnt exist

I have a left join query that shows all the fields from a primary table (tblMarkers) and the values from a second table (tblLocations) where there is matching record. 我有一个左联接查询,显示来自主表(tblMarkers)的所有字段和来自第二个表(tblLocations)的匹配记录的值。 tblLocations does not have a record for every id in tblMarkers tblLocations在tblMarkers中没有每个ID的记录

$query ="SELECT `tblMarkers`.*,`tblLocation`.*,`tblLocation`.`ID` AS `markerID`
FROM
   `tblMarkers`
 LEFT JOIN `tblLocation` ON `tblMarkers`.`ID` = `tblLocation`.`ID`
WHERE
`tblMarkers`.`ID` = $id";

I am comfortable with using UPDATE to update the tblMarkers fields but how do I update or INSERT a record into tblLocations if the record does not exist yet in tblLocations. 我对使用UPDATE来更新tblMarkers字段很满意,但是如果该记录在tblLocations中尚不存在,如何将记录更新或插入到tblLocations中。

Also, how do I lock the record I ma working on to prevent someone else from doing an update at the same time? 另外,如何锁定正在处理的记录以防止其他人同时进行更新?

Can I also use UPDATE tblMarkers * or do I have to list every field in the UPDATE statement? 我还可以使用UPDATE tblMarkers *还是必须列出UPDATE语句中的每个字段?

Unfortunately you might have to implement some validation in your outside script. 不幸的是,您可能必须在外部脚本中实施一些验证。 There is an IF statement in SQL, but I'm not sure if you can trigger different commands based on it's outcome. SQL中有一个IF语句,但是我不确定是否可以根据它的结果触发不同的命令。

Locking 锁定

In terms of locking, you have 2 options. 在锁定方面,您有2个选项。 for MyISAM tables, you can only lock the entire table using http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html 对于MyISAM表,您只能使用http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html锁定整个表

LOCK TABLE users;

For InnoDB tables, there is no explicit 'lock' for single rows, however you can use transactions, to get exclusive rights during the operation. 对于InnoDB表,单行没有显式的“锁定”,但是您可以使用事务在操作期间获取独占权限。 http://dev.mysql.com/doc/refman/5.0/en/innodb-locks-set.html http://dev.mysql.com/doc/refman/5.0/en/innodb-locks-set.html

Update 更新资料

There might be some shorthand notation, but I think you have to list every field in your query. 可能会有一些速记符号,但是我认为您必须列出查询中的每个字段。 Alternatively, you can always read the entire row, delete it and insert again using shorthand INSERT query. 或者,您始终可以读取整个行,将其删除,然后使用速记INSERT查询再次插入。 It all depends on how many fields you've got. 这完全取决于您拥有多少个字段。

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

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