mysql更新 跨 表,MySQL跨表更新

I have a users table and a sales table.

The users table has columns id and annual_plan_length, monthly_plan_length.

Example user row:

id | annual_plan_length | monthly_plan_length

55 | 0 | 0

The sales table has columns id, user_id, product

Example sales rows:

id | user_id | product

1 | 55 | monthly

2 | 55 | annually

I am trying to write a query to update the users plan length column according to how many purchases they've made using the sales table.

Here's what I got so far:

function updateLength($product, $column) {

global $emdb;

mysql_query("UPDATE users

JOIN sales

ON sales.user_id = users.id

SET users.`".mysql_real_escape_string($column)."` = count(sales.id) GROUP BY sales.user_id

WHERE sales.product = '".mysql_real_escape_string($product)."'", $emdb);

}

updateLength('monthly', 'annual_plan_length');

updateLength('annually', 'monthly_plan_length');

This query doesn't work, but with your help, this should end up putting a 1 on the columns monthly_plan_length and annual_plan_length for the user ID 55.

Ps.: I know PDO is better but it's not used yet for this client's project.

Ps.: Syntax error near GROUP BY

解决方案

You only can use GROUP BY in end your query. I see a problem on your query because you want to update every user that have a same product but with diferent values of purchases.

You need to remove GROUP BY .

Maybe it help you:

UPDATE users

JOIN sales

ON sales.user_id = users.id

SET users.annual_plan_length = (SELECT count(user_id) FROM sales WHERE user_id = 1 WHERE sales.product = 'monthly');

Because the edit should be 6 characters, here's what I did: I put the paren at the right place.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值