![](/img/trans.png)
[英]Taking ids from two rows of one MySQL table and entering those values in one row of another MySQL table using PHP
[英]Updating MySQL row with values from another table using PDOs
我有一个像下面这样的表,当前没有rating
, lib_id
或votes
。
图书馆
id | title | year | rating | votes | lib_id |
---------------------------------------------
1 | book1 | 1999 | | | |
2 | book2 | 2010 | | | |
3 | book3 | 2009 | | | |
4 | book4 | 2007 | | | |
5 | book5 | 1987 | | | |
然后,我得到了如下分类表。
分类
id | title | year | rating | votes | lib_id |
---------------------------------------------
108 | book154 | 1929 | | | |
322 | book23 | 2011 | | | |
311 | book3 | 2009 | 9.3 | 4056 | 10876 |
642 | book444 | 2001 | | | |
533 | book567 | 1981 | | | |
库表中的条目可能不会出现在分类表中,反之亦然。 本书的标题也可能不是唯一的。 因此,我想做的是遍历库表中的每一行,获取title
和year
列,转到classifications
表,找到具有这两个值的行,检索相应的rating
, votes
和lib_id
列并更新库表中的条目。
我也想使用PDO。 以下是我要实现的无效示例。
$update_vals_STH =
$DBH->prepare(
"UPDATE library SET lib_id=?, rating=?, votes=?
FROM (SELECT lib_id, rating, votes)
FROM classifications WHERE title=? AND year=?";
任何帮助,将不胜感激。 我对MySQL还是很陌生,并且已经为此苦苦挣扎了一段时间。
您也可以在更新语句上联接表。
UPDATE library a
INNER JOIN classifications b
ON a.title = b.title AND
a.year = b.year
SET a.rating = b.rating,
a.votes = b.votes,
a.lib_id = b.lib_id
// WHERE clause // if you want to have extra condition.
更新
为了获得更好的性能,您需要在以下字段上添加索引。
ALTER TABLE library ADD INDEX (title, year);
ALTER TABLE classifications ADD INDEX (title, year);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.