English 中文(简体)
如果在其他表格中没有记录, MySQL 更新
原标题:MySQL update if record does not exists in other table
  • 时间:2012-05-26 05:55:38
  •  标签:
  • mysql
  • sql

我正在设法弄清楚是否可以检查表B中是否有具体记录。 如果是的话,请不要更新表A。

我尝试了谷歌,但我只找到了插入版本,我不确定能否更新查询。

提前感谢

最佳回答
update table_to_update 
set some_column = 123
where id = 1
and id not in (select id from table_b)
问题回答

The following SQL statements function as a foreign key in where I add a new field in the daughter table with the condition that this value does not exist in a column of the master table.

UPDATE t1
SET c1 = ?
WHERE t1.id = ?
AND ? NOT IN (SELECT id FROM t2);

参数和表格的含义:

  • t1: daughter table
  • t2: master table
  • 1st ? : Value that will be established in the field of t1.c1 if the condition is met
  • 2nd ? : Identifier of the record where the field to be updated is located
  • 3rd ? : Value necessary to evaluate the condition, where I compare it with the field of t2

< 强 > > 第一参数和第三参数的值必须相同!

使用此语句时,当我们指主表格字段时,列必须有一个主密钥。这就是为什么与外国密钥相似的原因。


第二个备选方案还将是:

UPDATE t1 a
LEFT JOIN t2 b
ON b.column = ?
SET t1.c1 = ?
WHERE b.column IS NULL && a.id = ?;

< 加强> 第一和第二参数必须是相同的 。 在 < code> column 是主表一列的地方 。

“它们”另一方面,在使用此其他句子时,我们具有更大的灵活性,因为它不是主表列有一个主键的必要条件。

您也可以尝试使用 MySQL < a href="http://dev.mysql.com/doc/refman/ 5.0/ en/ existences-and-not- existences-subqueries.html" rel="nofollow" > sexistences 表达式。 旧的 MySQL 版本使用语法, 即 5. 0, 证明我比使用嵌套查询更快 。

update table_a
set some_column =  bla 
where not exists (select id
                        from table_b
                        where table_a.id = table_b.id)




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签