[英]Update a record in table1 if table2 has updates (MySQL)
In MySQL, I have 2 tables (currently MyISAM). 在MySQL中,我有2个表(当前为MyISAM)。 Let's call them table1 and table2.
我们称它们为table1和table2。
table1 has: table1具有:
id
passwd
full_name
email
table2 has: table2具有:
user_id
book (the book's title)
Basically, a user can rent books, and a row is created in table2, with records about the user_id, and the book title the user rented. 基本上,用户可以租用书籍,并在table2中创建一行,其中包含有关user_id和用户租用的书籍标题的记录。
In table1, I would like to add a column called 'books_rented'. 在表1中,我想添加一个名为“ books_rented”的列。
In PHP, I can calculate all the rows that x user_id has, and it will return how many books that person rented. 在PHP中,我可以计算x user_id的所有行,它将返回该人租用了多少本书。 However, I would like to know if it's possible to do that within MySQL itself, it would seem more optimal to me.
但是,我想知道是否有可能在MySQL本身中做到这一点,对我来说似乎更理想。
PS.: I am giving books as an example as I thought it would make it simpler, but the tables are actually employer/employee relational. PS .:我以举个例子为例,因为我认为这样会使事情变得更简单,但是表实际上是与雇主/雇员有关的。 If an employee deletes his account, then it won't really be optimal doing it with PHP as it would need to wait until the employer logs in again to update this.
如果员工删除了他的帐户,那么用PHP进行操作并不是最佳选择,因为它需要等到雇主再次登录才能更新它。 I can't really do this with PHP unless I run a cron job which I don't really like.
除非我运行我不太喜欢的cron作业,否则我真的不能用PHP做到这一点。
what is relation between that 2 tables, i assume that table1.id with table2.id. 那2个表之间是什么关系,我假设table1.id与table2.id。
update table1 set books_rented=(select count(*) from table2 where user_id=id)
Please try this at your dev machine first. 请首先在您的开发机器上尝试。
I think adding the books_rented
column is necessary. 我认为添加
books_rented
列是必要的。 You can just simply query
it to get the quantity of books that a specific user has rented. 您只需
query
它即可获取特定用户租用的图书数量。
SELECT T1.id
, T1.passwd
, T1.full_name
, T1.email
, IFNULL(COUNT(T2.book), 0) AS books_rented
FROM table1 T1
LEFT JOIN table2 T2 ON T2.user_id = T1.id
GROUP BY T1.id
I suggest that you work with your design, since there are instances that you will be: 我建议您使用设计,因为存在以下情况:
Since users
and books
are many to many relationship
, you need to add a JUNCTION TABLE . 由于
users
和books
存在many to many relationship
,因此需要添加一个JUNCTION TABLE 。 So you will end up with: users
, books
and userbooks
. 因此,您最终将获得:
users
, books
和users
userbooks
。
Triggers are exactly what I was looking for. 触发器正是我想要的。 Great tutorial about it .
很棒的教程 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.