Updating users table from complex SQL query, users.id not recognised? - mysql

So the other day, I asked this question about how to combine three complex queries and found a way to do it. Now I'm trying to use those queries to update a field in the users table and can't find a way to make it work. Here's the query:
update users set field_sum =(
select sum(field_sum) from (
select sum(field_one) as field_sum
from t_a join t_b on (t_a.bid = t_b.id) where t_b.user_id=users.id
union all
select sum(field_two) as field_sum
from t_c join t_d on (t_c.did = t_d.id) where t_d.user_id=users.id
union all
select sum(field_three) as field_sum
from t_e where t_e.user_id=users.id
) as field_sumT
)
When I try to run it, I get the following error: ERROR 1054 (42S22): Unknown column 'users.id' in 'where clause'. When I try removing the .user_id=users.id bit from each where clause, it will run but ends up with the total sum of field_sum, not just the field_sum for that user. Is there any way to accomplish this?

Use:
UPDATE USERS u
LEFT JOIN (SELECT t_b.user_id,
SUM(field_one) as field_sum
FROM t_a
JOIN t_b on t_a.bid = t_b.id
GROUP BY t_b.user_id) a ON a.user_id = u.id
LEFT JOIN (SELECT t_d.user_id,
SUM(field_two) as field_sum
FROM t_c
JOIN t_d on t_c.did = t_d.id
GROUP BY t_d.user_id) b ON b.user_id = u.id
LEFT JOIN (SELECT t_e.user_id,
SUM(field_three) as field_sum
from t_e
GROUP BY t_e.user_id) c ON c.user_id = u.id
SET field_num = COALESCE(a.field_sum, 0) + COALESCE(b.field_sum, 0) + COALESCE(c.field_sum, 0)
Caveat
This will set any users with no records in the supporting rows to have a field_sum value of zero. Do you only want to update those with a record in at least one of those tables?

Related

How to fix join error in mysql update query

I had an error in mysql as picture. please help me
sql code is following:
UPDATE
tbl_users AS Users
SET
Users.money_current = Users.money_current +
CASE
WHEN TempTbl.money_info IS NULL
THEN 0
ELSE TempTbl.money_info
END
LEFT JOIN
(SELECT
userId,
SUM(bet_money * bet_rate) AS money_info
FROM
tbl_betting
WHERE ROUND = 'xxx'
AND is_win = 1
GROUP BY userId) AS TempTbl
ON Users.userId = TempTbl.userId
FROM tbl_users AS Users;
This is the correct syntax:
UPDATE tbl_users AS Users
LEFT JOIN (
SELECT userId, SUM(bet_money * bet_rate) AS money_info
FROM tbl_betting WHERE ROUND = '965802' AND is_win = 1
GROUP BY userId
) AS TempTbl ON Users.userId = TempTbl.userId
SET Users.money_current = Users.money_current + COALESCE(TempTbl.money_info, 0)
I also changed that CASE expression with COALESCE().
But I think an INNER JOIN would also work in your case, since the unmatched rows of the LEFT JOIN that you use do not change the value of money_current.

SQL Join gives wrong results (creates duplicates)

I have a problem with my SQL join query. I have looked up other suggested answers and tried to apply it to my query, but it doesn't seem to be working.
I have this query:
SELECT SUM(p.quantity)
FROM stocktake_scans p
LEFT JOIN (
SELECT stocktake_area_id
FROM stocktake_areas
WHERE stocktake_id =8592 AND area_checked = 1
)d ON d.stocktake_area_id = p.stocktake_area_id
LEFT JOIN (
SELECT user_id
FROM stocktake_scan_edit
WHERE user_id =46521
)e ON e.user_id = p.stocktake_staff_id
WHERE p.stocktake_staff_id = 46521
And it gives me a result of 42, while I should get only 6. What is missing from the query?
I think you may have extra records with the same ID in your joined table that is where you are getting multiple rows returned from which is then calculating wrong in your sum, please try the below.
SELECT SUM(p.quantity) FROM stocktake_scans p LEFT JOIN ( SELECT distinct stocktake_area_id FROM stocktake_areas WHERE stocktake_id =8592 AND area_checked = 1 )d ON d.stocktake_area_id = p.stocktake_area_id LEFT JOIN ( SELECT distinct user_id FROM stocktake_scan_edit WHERE user_id =46521 )e ON e.user_id = p.stocktake_staff_id WHERE p.stocktake_staff_id = 46521

MySQL Query, (access mainquery from subquery)

I have a problem that I need a WHERE clause in a subquery that depends on the results of the main Query, otherwise my results would be wrong and the query takes too long / is not executeable.
The circumstances that I need this query to create a view which I need for a search server support the problem that I cannot split this into two queries, nor process it with a script dynamically.
The problem occurs with the following query:
SELECT `s`.`id` AS `seminar_id`, (SUM( `sub`.`seminar_rate` ) / COUNT( `sub`.`seminar_id` )) AS `total_rate`
FROM
(
SELECT (SUM( value ) / COUNT( * )) AS `seminar_rate` , `r`.`seminar_id`
FROM `rating` r
INNER JOIN `rating_item` ri ON `r`.`id` = `ri`.`rating_id`
WHERE `r`.`seminar_id` = `s`.`id`/* <- Here is my problem, this is inacessible */
GROUP BY `r`.`seminar_id`
) AS sub,
`seminar` s
INNER JOIN `date` d
ON `s`.`id` = `d`.`seminar_id`
INNER JOIN `date_unit` du
ON `d`.`id` = `du`.`date_id`
LEFT JOIN `seminar_subject` su
ON `s`.`id` = `su`.`seminar_id`
LEFT JOIN `subject` suj
ON `su`.`subject_id` = `suj`.`id`
INNER JOIN `user` u
ON `s`.`user_id` = `u`.`id`
INNER JOIN `company` c
ON `u`.`company_id` = `c`.`id`
GROUP BY `du`.`date_id`, `sub`.`seminar_id`
This query should calculate a total rate out of ratings for each Seminar.
However my ratings are stored in my "rating" table and should be processed live.
(Sidenote: If you wonder about all the joins: This query has alooot more SELECT'ed fields, I just removed them because they are not nesessary to solve the problem and to make the query look less complicated [I know it still is >.>]...)
The reason is that I want this results to be sortable by my search engine later depending
on the users sort parameters, thatswhy I need it inside this query.
The problem itself is pretty obvious:
ERROR 1054 (42S22): Unknown column 's.id' in 'where clause'
The subselect doesnt know about the results of the main query, is there a solution to bypass this?
Could someone give me a hint to get this working?
Thanks in advance.
Using your subquery in the JOIN you can eliminate the WHERE clause and achieve nearly the same result. Here is your modified query. Hope this solves your problem.
SELECT `s`.`id` AS `seminar_id`, (SUM( `sub`.`seminar_rate` ) / COUNT( `sub`.`seminar_id` )) AS `total_rate`
FROM `seminar` s
INNER JOIN
(
SELECT (SUM( value ) / COUNT( * )) AS `seminar_rate` , `r`.`seminar_id`
FROM `rating` r
INNER JOIN `rating_item` ri ON `r`.`id` = `ri`.`rating_id`
/*WHERE `r`.`seminar_id` = `s`.`id` <- Here is my problem, this is inacessible */
GROUP BY `r`.`seminar_id`
) AS sub ON s.id = sub.`seminar_id`
INNER JOIN `date` d
ON `s`.`id` = `d`.`seminar_id`
INNER JOIN `date_unit` du
ON `d`.`id` = `du`.`date_id`
LEFT JOIN `seminar_subject` su
ON `s`.`id` = `su`.`seminar_id`
LEFT JOIN `subject` suj
ON `su`.`subject_id` = `suj`.`id`
INNER JOIN `user` u
ON `s`.`user_id` = `u`.`id`
INNER JOIN `company` c
ON `u`.`company_id` = `c`.`id`
GROUP BY `du`.`date_id`, `sub`.`seminar_id`

Outer Join in mYsql Qyery

I have folowing MYsql Query And Trying to right outer join but unable to understan how to do this
here is query plase any one help
select lp_des.lpname,today.cnt_veh_tdy,todate.cnt_veh_tdate
from
(select distinct registration.lpcode,loadingpoint.lpname
from registration,loadingpoint
where registration.lpcode=loadingpoint.lpcode) lp_des,
(select lpcode,count(vehicleno) cnt_veh_tdate
from registration
where registration.companycode='01'
group by lpcode) todate,
(
select lpcode,count(vehicleno) cnt_veh_tdy
from registration
where registration.companycode='01'
and registration.date=(select max(date) from registration)
group by lpcode) today
right outer join today on lp_des.lpcode = today.lpcode
right outer join todate on lp_des.lpcode = todate.lpcode
I want to make right outer join on this part
where lp_des.lpcode=todate.lpcode
and lp_des.lpcode=today.lpcode
Please help and Thanks in advance
You asked for this:
select
lp_des.lpname,
today.cnt_veh_tdy,
todate.cnt_veh_tdate
from
(select distinct
r.lpcode,
l.lpname
from
registration r
inner join loadingpoint l on l.lpcode = r.lpcode) lp_des
right join
(select
r.lpcode,
count(r.vehicleno) cnt_veh_tdate
from
registration r
where
r.companycode='01'
group by
lpcode) todate on todate.lpcode = lp_des.lpcode
right join
(select
r.lpcode,
count(r.vehicleno) cnt_veh_tdy
from
registration r
where
r.companycode = '01'
and registration.date = (select max(date) from registration)
group by
r.lpcode) today on today.lpcode = lp_des.lpcode
But I think you mean this:
select
r.lpcode,
l.lpname,
count(r.vehicleno) cnt_veh_tdate,
count(case when r.date = md.date then r.vehicleno else null end) cnt_veh_tdy
from
registration r
inner join (select max(rm.date) maxdate from registration rm) md
left join loadingpoint l on l.lpcode = r.lpcode
where
r.companycode = '01'
group by
r.lpcode
and maybe even this:
select
r.lpcode,
l.lpname,
count(r.vehicleno) cnt_veh_tdate,
count(case when r.date = date() then r.vehicleno else null end) cnt_veh_tdy
from
registration r
left join loadingpoint l on l.lpcode = r.lpcode
where
r.companycode = '01'
group by
r.lpcode
If I read it correctly, you want a query that returns the number of vehicles for company 1 assigned to a loading point, overall as well as for today only. And you also want that count for vehicles that do not have loading point assigned yet.
Though it would help if you would have added this description. It will help the ones answering your question, but it will also help you writing the right query in the first place.
The syntax for a right outer join is:
SELECT t1.id, t2.id FROM t1 RIGHT OUTER JOIN t2 ON t1.field1 = t2.field2
If you're joining on the same field you can use USING instead of ON:
SELECT t1.id, t2.id FROM t1 RIGHT OUTER JOIN t2 USING (field)

Mysql query, select 2 databases with 4 tables + nested SELECT?

This is my current query:
$sel = "SELECT
db1t1.userid, db1t1.customer_id, db2t1.customers_id, db2t1.orders_id, db2t2.products_price
FROM
database1.table1 db1t1
LEFT JOIN database2.table1 db2t1 ON
db1t1.customer_id = db2t1.customers_id
LEFT JOIN database2.table2 db2t2 ON
db2t1.orders_id = db2t2.orders_id
WHERE db1t1.userid IN(
SELECT
l.userid, l.username, r.username, r.cus_id
FROM
database1.table3 l
LEFT JOIN database2.table4 r ON
l.username = r.username
WHERE r.cus_id = '1234'
)";
Error message:
Operand should contain 1 column(s)
The error occurred because that you returned a result with multiple columns to an IN clause.
Try this:
SELECT
`db1t1`.`userid`, `db1t1`.`customer_id`, `db2t1`.`customers_id`,
`db2t1`.`orders_id`, `db2t2`.`products_price`
FROM `database1`.`table1` AS `db1t1`
LEFT JOIN `database2`.`table1` AS `db2t1`
USING (`customers_id`)
LEFT JOIN `database2`.`table2` AS `db2t2`
USING (`orders_id`)
WHERE `db1t1`.`userid` IN (
SELECT `l`.`userid`
FROM `database1`.`table3` AS `l`
LEFT JOIN `database2`.`table4` AS `r`
USING (`username`)
WHERE `r`.`cus_id` = 1234
)
What are you trying to achieve ? Maybe we can find a better solution.
Also, I think that you should do an INNER JOIN instead of a LEFT JOIN in the subquery.