在drupal中帮助db查询 - 如果存在update else insert [英] Help with db query in drupal - if exists update else insert

查看:103
本文介绍了在drupal中帮助db查询 - 如果存在update else insert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在drupal中运行一个查询,如果它们已经存在或者插入一个新的条目(如果没有)则会更新条目。代码看起来像这样:

I've been trying to run a query in drupal that'll update entries if they already exists or insert a new entry if it doesnt. The code looks like this at the moment:

db_query("IF EXISTS (SELECT %d FROM {uc_posten_packages.pid})
UPDATE {uc_posten_packages} SET title = '%s', label = '%s', cost = '%d', length = '%d', width ='%d', height = '%d', weight = '%d'  WHERE pid = %d
ELSE
INSERT INTO {uc_posten_packages} VALUES ('%d', '%s', '%s', '%d', '%d', '%d', '%d', '%d')",$id, $title, $label, $rate, $length, $width, $height, $weight, $id, $id, $title, $label, $rate, $length, $width, $height, $weight);

我不明白为什么这个查询会给我一个错误。错误中的所有数字都是正确的

I can't see why that query throws me an error. All the numbers in the error are correct

...near 'IF EXISTS (SELECT 1 FROM uc_posten_packages.pid) UPDATE uc_posten_packages ' at line 1 query:
IF EXISTS (SELECT 1 FROM uc_posten_packages.pid) UPDATE uc_posten_packages SET title = 'vfbv', label = 'bbv', cost = '22', length = '232', width ='22', height = '22', weight = '22' WHERE pid = 1 ELSE INSERT INTO uc_posten_packages VALUES ('1', 'vfbv', 'bbv', '22', '232', '22', '22', '22')

如果这个查询工作和/或有更好的方法处理这个drupal?

Should this query work and/or is there some better way dealing with this in drupal?

推荐答案

您正在寻找的是诚挚的称为upsert(否则插入更新),还有drupal函数只是这样:db_merge。这里写的很好: http://drupal.org/node/310085

What you're looking for is cordially called an "upsert" (update otherwise insert), and there is a drupal function for just this: db_merge. Good write-up here: http://drupal.org/node/310085

drupal_write_record()不会自动执行upsert。它总是根据您传递的内容插入或更新,但不能同时插入或更新。

drupal_write_record() does not automatically perform an "upsert." It always either inserts or updates based on what you pass in only, but not both.

这篇关于在drupal中帮助db查询 - 如果存在update else insert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆