学
+-----+-----------+----------+
| id | the_photo | column3 |
+-----+-----------+----------+
| 11 | NULL | abc |
| 22 | NULL | asf |
| 33 | NULL | asag |
+-----+-----------+----------+
school_images
+-----+-----------+-------+
| id | school_id | photo |
+-----+-----------+-------+
| 1 | 11 | 1 |
| 2 | 22 | 0 |
| 3 | 33 | 1 |
+-----+-----------+-------+
...
只有当照片值= 1时才需要将值插入学校的the_photo列,例如:school_images:
学校
+-----+-----------+
| id | the_photo |
+-----+-----------+
| 11 | 1 |
| 22 | NULL |
| 33 | 3 |
+-----+-----------+
是否可以编写一个简单的查询来为所有行执行此操作?对于一行我知道如何插入它,但我怎么能自动惰性多行。
答案 0 :(得分:0)
UPDATE school AS s, school_images AS si SET s.the_photo = si.id WHERE s.id = si.school_id AND si.photo = 1;
答案 1 :(得分:0)
这可能是您正在寻找的内容:SELECT INTO。 取自链接:
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
答案 2 :(得分:0)
请注意!! 只有在您想要在新插入时执行上述请求的操作时,此答案才有效。否则,您将需要一个不同的策略
你应该有这样的东西:
从school_images
中选择所有值,然后预测它们:
foreach($result as $res) {
if($res['photo'] == 1) {
// see step 2
} else {
// see step 3
}
}
如果你在school_photos中的值为1,那么:
INSERT INTO school (the_photo, colum3) VALUES ($res['id'], $some_value)
答案 3 :(得分:0)
您也可以使用内部联接来实现这一目标。
Update School inner join school_images on School.id = school_images.school_id and photo=1
set the_photo = school_images.id ;
答案 4 :(得分:0)
您应该使用INNER JOIN将school
加入school_images
:
UPDATE
school INNER JOIN school_images
ON school.id = school_images.school_id
AND school_images.photo=1
SET
school.the_photo=school_images.id