Updating row from select results [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am on a project of which requires Ranking and outputing the total score to users.
I have a table called userdata like this
id matricno mtstotal engtotal grandtotal Rank
1 MXX001 6 4
2 MXX002 9 8
3 MXX003 5 3
4 MXX004 4 7
5 MXX005 7 2
SELECT * FROM (
SELECT s.*, #rank := #rank + 1 rank FROM (
SELECT matricno, sum(mtstotal + engtotal) TotalPoints FROM userdata
WHERE class='1' AND subclass='A'
GROUP BY matricno
) s, (SELECT #rank := 0) init
ORDER BY TotalPoints DESC
) r
This SQL creates something temporary
matricno TotalPoints rank
MXX002 17 1
MXX004 11 2
MXX001 10 3
MXX005 9 4
MXX003 8 5
What I want is a statement added to the one above that will copy the TotalPoints and rank values and update the grandtotal and Rank columns respectively.
Even if it is formatting another code but it should be able to sum, rank and update in one single coding

When updating userdata join it with your query as subselect and use values from it
UPDATE userdata ud
JOIN(
SELECT s.*, #rank := #rank + 1 rank FROM (
SELECT matricno, sum(mtstotal + engtotal) TotalPoints FROM userdata
WHERE class='1' AND subclass='A'
GROUP BY matricno
) s, (SELECT #rank := 0) init
ORDER BY TotalPoints DESC
) r ON r.matricno = ud.matricno
SET ud.grandtotal = r.TotalPoints,
ud.Rank = r.rank

Related

How to left join then get the latest row in second table using where date [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Is anyone know how to query this example table?
Images on imgur
I think it is a left join from the table branches to the table branch_operationals which I need to put where date inside the query.
Here are the examples:
TABLE branches
id
code
name
1
T2QD5
NewYork_Spot
2
MKGHB
London_Spot
3
IGHCZ
Miami_Spot
4
PJDSO
Tokyo_Spot
TABLE branch_operationals
id
branch_id
date
status
1
2
2020-12-05
closed
2
2
2020-12-06
closed
3
3
2020-12-06
open
4
2
2020-12-06
closed
5
2
2020-12-06
open
6
1
2020-12-16
closed
EXPECTED RESULT
id (from 'branches.id')
code
name
date
status
1
T2QD5
NewYork_Spot
2020-12-09
closed
2
MKGHB
London_Spot
2020-12-09
open
3
IGHCZ
Miami_Spot
2020-12-09
open
4
PJDSO
Tokyo_Spot
2020-12-09
null
And here is my current query:
select * from `branches` left join `branch_operationals` on `branches`.`id` = `branch_operationals`.`branch_id` where (`date` = 2020-12-21)
However, it returns null (empty data). But when I remove the where statement, it shows all data from the table branch_operationals with each data from table branches.
Currently I am using Laravel 8, and here is my Laravel syntax:
$branches = Branch::leftJoin('branch_operationals','branches.id','branch_operationals.branch_id')->where(function($q) use($request){
if($request->search){
$q->where(function($q) use($request){
$q->where('code','like','%'.$request->search.'%');
$q->orWhere('name','like','%'.$request->search.'%');
});
}
if($request->date_filter){
$q->where('date',$request->date_filter);
}else{
$q->where('date',\Carbon\Carbon::now()->toDateString());
}
})->get();
I need the query syntax or the Laravel Eloquent syntax.
I can provide you the query syntax which is normal LEFT JOIN.
The issue with your query is that you are doing INNER JOIN by applying the condition on the Left joined table in the WHERE clause. You can achieve the desired result as follows:
select * from
(select b.*, bo.*, -- use the needed column names with proper alias here. I have used *
row_number() over (partition by b.id order by bo.date desc) as rn
from branches b
left join branch_operationals bo on b.id = bo.branch_id and date <= 2020-12-21) t
where rn = 1
maybe it will work for you
select b.id ,b.code,b.name ,'2020-12-06' date ,o.status from branch b
left join ( select bo.id, bo.branch_id, bo.date, bo.status from
(select branch_id , max(id) id from branch_operationals where date='2020-12-06' group by branch_id ) as tmp
join branch_operationals bo on bo.id=tmp.id ) as o on b.id=o.branch_id

Query for update stock quantity in transaction [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm having trouble with my query because I have to deduct the quantity of the product from a different stock_code.
Let say the customer will buy a product in item_code (I0015) for 20 quantities. First I want to deduct the 12 quantities to the stock_code (ST0016) and the stock will become 0, and the remaining 8 quantities will deduct in stock_code (ST0012), the deduction of quantity is based on the ascending date of stock_expired.
How do I query that in MySQL? Thank you so much! The answer is highly appreciated. The name of my table is stocks_table
Is code below the solution (fiddle)?
with cte as(
select * from(
select *, case when cumulsum <= TotalRequiredQuantity then 0 else cumulsum-TotalRequiredQuantity end NewQuantity
from(
select *, 20 TotalRequiredQuantity,/*Set valid quantitity*/
sum(stock_quantity) over(partition by item_code order by stock_expired) cumulsum
from stocks_table
where item_code = 'I0015'/*Set valid item_code*/
)q
)q1
where stock_quantity>=NewQuantity)
update stocks_table st
join cte on st.id=cte.id
set st.stock_quantity = NewQuantity
without common table expression:
update stocks_table st
join(
select * from(
select *
,case when cumulsum <= TotalRequiredQuantity then 0 else cumulsum-TotalRequiredQuantity end NewQuantity
from(
select *, 20 TotalRequiredQuantity,/*Set valid quantitity*/
sum(stock_quantity) over(partition by item_code order by stock_expired) cumulsum
from stocks_table
where item_code = 'I0015'/*Set valid item_code*/
)q
)q1
where stock_quantity>=NewQuantity
)cte on st.id=cte.id
set st.stock_quantity = NewQuantity

mysql query of union and mysql_num_rows [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
SELECT tbl_post_upvote.id AS i ,
COUNT(user_id) AS c
FROM tbl_post_upvote
LEFT JOIN tbl_post ON (tbl_post.id=tbl_post_upvote.post_id)
WHERE tbl_post.author_id = 3 and is_seen = 0
UNION
SELECT tbl_post_downvote.id AS i,
COUNT(user_id)
FROM tbl_post_downvote
LEFT JOIN tbl_post ON (tbl_post.id=tbl_post_downvote.post_id)
WHERE tbl_post.author_id=3 and is_seen=0
$r_noti = mysql_query($sq_noti);
$l = mysql_fetch_assoc($r_noti);
$l_noti = mysql_num_rows($r_noti);
if ($l['c'] > 0 && $l['i']!=0) { ?>
<span class="badge">
<?= $l_noti; ?>
</span>
<?php } ?>
It displays result
i value 6 , 0
and c value 1 , 0 respectively.
i want to remove 0 ,0 row
and result is i value 6 and c value 1 only
You have to add GROUP BY i to your statements.
Please try the following:
select tbl_post_upvote.id as i ,count(user_id) as c
from tbl_post_upvote left join
tbl_post
on (tbl_post.id=tbl_post_upvote.post_id)
where tbl_post.author_id=3 and is_seen=0
group by i
union
select tbl_post_downvote.id as i,count(user_id)
from tbl_post_downvote left join
tbl_post
on (tbl_post.id=tbl_post_downvote.post_id)
where tbl_post.author_id=3 and is_seen=0
group by i

MySQL, check if result has value, if not take another [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a table structure like this:
Page_id || type || user_id
1 1 0
2 2 0
3 3 0
4 1 1
5 2 1
6 3 1
From this table I would like to get page_id 4,5 and 6.
But I can also have table data like this
Page_id || type || user_id
1 1 0
2 2 0
3 3 0
4 1 1
5 2 1
Then I would like to get page_id 4, 5 and 3.
So I have to get all the types, but with the priority user_id and if there is no record with user_id 1, then take the one with 0
Have tried a lot. I know I can sort it with PHP, but I hope there is a way with MySQL.
Regards Andreas
//////// ANSWER /////////
I got a lot of suggestions, and I haven't tried them all, so I can't tell it they where right or not. But I have accepted an answer, which worked for me.Thank to everybody.
SELECT a.Type, a.Page_ID
FROM table a
INNER JOIN
(SELECT Type, MAX(User_ID) AS User_ID
FROM table
GROUP BY Type ) b
ON a.Type = b.Type AND a.User_ID = b.User_ID
You can execute a SELECT query as follow
SELECT Page_id
FROM table
WHERE user_id != 0
This SQL Fiddle demonstrates the below query:
SELECT DISTINCT
(
SELECT s1.Page_id
FROM myTable AS s1
WHERE m.type = s1.type
ORDER BY s1.Page_id
LIMIT 1
) AS PageID, type,
(
SELECT s2.user_id
FROM myTable AS s2
WHERE m.type = s2.type
ORDER BY s2.Page_id
LIMIT 1
) AS User
FROM myTable AS m
The results are the records where Page_id is 1, 2, and 4. As you can see in both of the sub queries I am ordering by Page_id to make sure the data is pulled from the same record and the first Page_id for that occurrence of the type is selected.
To return only one record unique to a couple columns, you'll want to use the GROUP BY statement. Then for any other column outside of the group by columns, you need to pick an aggregate function so it knows how to summarize the value if it finds multiple records in that group. In this case you want non-zero, so max() would work
SELECT type, max(user_id) as user_id
FROM table
GROUP BY type
how about that?
select page_id,type from (
select page_id,type, user_id from mytable
group by page_id,type, user_id having user_id=max(user_id)
) as x where user_id=1
Will there ever be multiple rows for a page where user_id is not zero? Because if not (if at most you only have one row per page where user_id = 1) then this will work:
SELECT ifNull(t1.page_id,t2.page_id) as page_id, t1.type,
CASE WHEN t2.page_id IS NULL THEN t1.user_id ELSE t2.user_id END as user_id
#start with all rows (including duplicates)
FROM myTable t1
#look for a user_id > 0 for this type
LEFT OUTER JOIN myTable t2 ON t1.type = t2.type AND t2.user_id > 0
WHERE t2.page_id IS NULL # if no record with user_id > 0 found, then no need to filter
# if a record with user_id > 0 was found, then filer out the user_id = 0 record
OR (t2.page_id IS NOT NULL AND t1.user_id > 0)
See in SQLFiddle: http://sqlfiddle.com/#!2/ba877/5

MySQL Updating column based on other values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am building a simple gaming system and I was wondering how to get the users rank without calculating everytime the result in a query(maybe I should run a cron job?).
This is my points table structure at the moment:
+--username--+--rank--+--total_points--+
|######################################|
| Mark | 0 | 700 |
|------------+--------+----------------|
| Luke | 0 | 400 |
+------------+--------+----------------+
How do I update the rank column based on total_points?
Is there a better way to do this? Thank you for your time
You need only one query:
UPDATE
users,
(SELECT
#row:=#row+1 rownum,
username
FROM users,
(SELECT #row := 0) r
ORDER BY total_points DESC) as rank_ord
SET users.rank = rank_ord.row
WHERE users.username = rank.username;
If your table contains an index column (other then username), then change the condition
WHERE users.username = rank.username
to
WHERE users.id = rank.id
to make it faster.
Assuming that the rank depends on total_points you just need to sort query results by total_points DESC and row number is your position in rank. No need to calculate anything. Of course you may have two users with same total_points so if you want to have same rank this will not work, but you can do pretty simple the same approach (pseudo code):
$rows = query with order total_points DESC
$rank = 0;
$last_total_points = -1;
foreach( $rows as $row ) {
if( $row['total_points'] != $last_total_points ) {
$rank++;
$last_total_points = $row['total_points'];
}
update that row with $rank;
}
so at the end, you will get all users ranked with the same rank for equal total_points values too

Categories