我有2张这样的表:
table_com
-------------
id_com|code|value|
----------------
1 |10 | A
2 |20 | B
table_b
----------
id_b|code
----------
1 |10
2 |20
3 |30
我想在table_com
中插入table_b
,而不是table_com
中的code
(根据id_b==3
)插入table_a
,例如table_com
1}},因为代码= 30它不存在于table_com
-------------
id_com|code|value|
-----------------
1 |10 | A
2 |20 | B
3 |30 | 0
中,对于值,我需要输入0.最终的foreach ($comunas as $key => $value) {
$code = $value->code;
DB::select(DB::raw("
INSERT INTO rgl_clientes_comuna (
code,
value
)
VALUES
($code, 0,)
WHERE code IS NOT $code
"));
}
应该是这样的:
INSERT INTO rgl_clientes_comuna (
comuna_id,
numero_clientes
) SELECT
cod_comuna,
0
FROM
rgl_cut ON DUPLICATE KEY UPDATE comuna_id = 12201
我正在使用php,我尝试了table_b的foreach值并尝试按照我的说法插入值,但不知道该怎么做(我知道使用INSERT INTO我无法使用在哪里,这只是一个例子):
#include <string.h>
#include <stdio.h>
int try_null (char []);
int main ()
{
char a [10];
char *ap = a;
strcpy(ap, "123.txt");
printf("length is %d\n", try_null(ap));
//This part doesn't give me a segmentation fault
/*char a [10];
strcpy(a, "123.txt");
int counter = 0, length = strlen(a);
for (counter = 0; counter < length; ++counter)
{
if ( (a[counter] >= 48) && (a[counter] <= 57) ); //if the value is a decimal leave it
else
a[counter]='\0'; //replace the first non decimal value with a null
}
length=strlen(a);
printf("%d\n", length); */
}
try_null(char value [10])
{
int counter, length = strlen(value); //find the current length of the array
printf("value is %d\n", length);
for (counter = 0; counter < length; ++counter)
printf("value is %c\n", value[counter]);
//getting rid of non-decimals
for (counter = 0; counter < length; ++counter)
{
if ( (value[counter] >= 48) && (value[counter] <= 57) ); //if the value is a decimal leave it
else
{
value[counter]='\0'; //replace the first non decimal value with a null
}
}
length=strlen(value);
return length;
}
编辑:
1)对于第一个答案,我尝试了这个(用我的真实数据):
static final String STATE_USER = "user";
private String mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mUser = savedInstanceState.getString(STATE_USER);
} else {
// Probably initialize members with default values for a new instance
mUser = "NewUser";
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
它有效,但它为table_b上的每个注册表添加了一个新行
答案 0 :(得分:2)
我只会使用insert into a (code, value)
select code, 0
from b
on duplicate key update code = values(code);
:
a(code)
为此,您需要{{1}}上的唯一索引/约束。
答案 1 :(得分:1)
这个怎么样?
insert into table_com
select id_b, code, 0
from table_b where id_b not in (select id_com from table_com);
还是这个?
insert into table_com
select id_b, code, 0
from table_b where code not in (select code from table_com);
因为我不清楚决定因素是否存在id
或code