get record in sql - mysql

I have a table with the following fields:
SELECT `sms_id`,
`u_id`,
`sender_id`,
`mobile_no`,
`message`,
`campaign_name`,
`status`,
`request_id`,
`route_id`,
`totalnumber`,
`msgcreadit`,
`date1`,
`deductbal`,
`submited`
FROM `send_sms`
WHERE 1
I want to select u_id whose status ="pending", but I want the latest pending status according to the [date1] date field and I also want the count of individual u_ids with status ="pending".
How can I do it?

In MySQL you can do:
SELECT s.*
FROM `send_sms` s
WHERE s.status = 'pending' AND
s.date1 = (SELECT MAX(s2.date1) FROM send_sms s2 WHERE s2.u_id = s.u_id and s2.status = 'pending');

Just another approach:
SELECT s.*
FROM `send_sms` s
LEFT JOIN `send_sms` s2
ON s.date1 < s2.date1
AND s2.u_id = s.u_id
AND s2.status = 'pending'
WHERE s.status = 'pending'
AND s2.status IS NULL

Related

SQL query for Update table using Join & Group By

I have used this to get Data
SELECT customers.*, COUNT(invoice.payment_status) AS pending_invoices,sum(invoice.total ) AS total_pending_amount
FROM customers JOIN invoice ON (invoice.customer_id = customers.id)
WHERE invoice.payment_status = 'P' AND invoice.status = 'A' AND payment_followup_date IS NOT NULL AND payment_followup_date <= '2022-03-24 23:59'
GROUP BY invoice.customer_id
ORDER By payment_followup_date DESC
Now I am looking for a Query to perform an update on customers to add the current DateTime into payment_payment_followup_date and payment status = P for those customers who have more than 3 pending invoices
Try this:
UPDATE customers c
INNER JOIN (
SELECT
customer_id, COUNT(payment_status) pending_invoices
FROM invoice
WHERE payment_status = 'P' AND status = 'A'
GROUP BY customer_id
HAVING COUNT(payment_status) > 3
) i ON c.customer_id = i.customer_id
SET c.payment_payment_followup_date = CURRENT_TIMESTAMP()
c.payment_status = 'P'
WHERE c.payment_followup_date IS NOT NULL
AND c.payment_followup_date <= '2022-03-24 23:59'

Update a column in mysql based on where statement with subselects

I have this pseudo SQL code for what I want to achieve:
UPDATE orders o
SET o.datePaid = null
WHERE
(
SELECT SUM(amount)
FROM transactions t
WHERE t.orderId = o.id
AND t.status = 'success'
AND t.type = 'refund'
)
>=
(
SELECT SUM(amount)
FROM transactions t
WHERE t.orderId = o.id
AND t.status = 'success'
AND t.type IN ('purchase', 'capture')
)
How would I do this in SQL?
I think your approach is interesting. Here is a more concise method:
UPDATE orders o
SET o.datePaid = null
WHERE (SELECT SUM(CASE WHEN t.type = 'refund' THEN amount
WHEN t.type IN ('purchase', 'capture') THEN -amount
END)
FROM transactions t
WHERE t.orderId = o.id AND
t.status = 'success'
) > 0;
Your query works fine as is. However it can be more optimally written using MySQL multi-table UPDATE syntax:
UPDATE orders o
LEFT JOIN (SELECT orderId,
COALESCE(SUM(CASE WHEN type = 'refund' THEN amount END), 0) AS refunds,
COALESCE(SUM(CASE WHEN type IN ('purchase', 'capture') THEN amount END), 0) AS pc
FROM transactions
WHERE status = 'success'
GROUP BY orderId) t ON t.orderId = o.id
SET o.datePaid = NULL
WHERE t.refunds > t.pc
Demo on dbfiddle (includes your query working as well)
Your code would probably work just as it is. Give it a try.
You could also optimize the query to avoid the need for two subqueries by using a JOIN and conditional aggregation in a single subquery:
UPDATE orders o
INNER JOIN (
SELECT orderId
FROM transactions
WHERE
status = 'success'
AND type IN ('success', 'purchase', 'capture') -- this condition might be superfuous
GROUP BY o.id
HAVING
SUM(CASE WHEN type = 'success' THEN amount ELSE 0 END)
>= SUM(CASE WHEN type IN ('purchase', 'capture') THEN amount ELSE 0 END)
) t ON t.orderId = o.id
SET o.datePaid = null
Note: WHERE condition AND type IN ('success', 'purchase', 'capture') is superfluous if that list of 3 values represents all the possible values.

MySQL query taking too much time

query taking 1 minute to fetch results
SELECT
`jp`.`id`,
`jp`.`title` AS game_title,
`jp`.`game_type`,
`jp`.`state_abb` AS game_state,
`jp`.`location` AS game_city,
`jp`.`zipcode` AS game_zipcode,
`jp`.`modified_on`,
`jp`.`posted_on`,
`jp`.`game_referal_amount`,
`jp`.`games_referal_amount_type`,
`jp`.`status`,
`jp`.`is_flaged`,
`u`.`id` AS employer_id,
`u`.`email` AS employer_email,
`u`.`name` AS employer_name,
`jf`.`name` AS game_function,
`jp`.`game_freeze_status`,
`jp`.`game_statistics`,
`jp`.`ats_value`,
`jp`.`integration_id`,
`u`.`account_manager_id`,
`jp`.`model_game`,
`jp`.`group_id`,
(CASE
WHEN jp.group_id != '0' THEN gm.group_name
ELSE 'NA'
END) AS group_name,
`jp`.`priority_game`,
(CASE
WHEN jp.country != 'US' THEN jp.country_name
ELSE ''
END) AS game_country,
IFNULL((CASE
WHEN
`jp`.`account_manager_id` IS NULL
OR `jp`.`account_manager_id` = 0
THEN
(SELECT
(CASE
WHEN
account_manager_id IS NULL
OR account_manager_id = 0
THEN
`u`.`account_manager_id`
ELSE account_manager_id
END) AS account_manager_id
FROM
user_user
WHERE
id = (SELECT
user_id
FROM
game_user_assigned
WHERE
game_id = `jp`.`id`
LIMIT 1))
ELSE `jp`.`account_manager_id`
END),
`u`.`account_manager_id`) AS acc,
(SELECT
COUNT(recach_limit_id)
FROM
recach_limit
WHERE
recach_limit = '1'
AND recach_limit_game_id = rpr.recach_limit_game_id) AS somewhatgame,
(SELECT
COUNT(recach_limit_id)
FROM
recach_limit
WHERE
recach_limit = '2'
AND recach_limit_game_id = rpr.recach_limit_game_id) AS verygamecommitted,
(SELECT
COUNT(recach_limit_id)
FROM
recach_limit
WHERE
recach_limit = '3'
AND recach_limit_game_id = rpr.recach_limit_game_id) AS notgame,
(SELECT
COUNT(joa.id) AS applicationcount
FROM
game_refer_to_member jrmm
INNER JOIN
game_refer jrr ON jrr.id = jrmm.rid
INNER JOIN
game_applied joa ON jrmm.id = joa.referred_by
WHERE
jrmm.STATUS = '1'
AND jrr.referby_user_id IN (SELECT
ab_testing_user_id
FROM
ab_testing)
AND joa.game_post_id = rpr.recach_limit_game_id
AND (rpr.recach_limit = 1
OR rpr.recach_limit = 2)) AS gamecount
FROM
(`game_post` AS jp)
JOIN
`user_info` AS u ON `jp`.`user_user_id` = `u`.`id`
JOIN
`game_functional` jf ON `jp`.`game_functional_id` = `jf`.`id`
LEFT JOIN
`group_musesm` gm ON `gm`.`group_id` = `jp`.`group_id`
LEFT JOIN
`recach_limit` rpr ON `jp`.`id` = `rpr`.`recach_limit_game_id`
WHERE
`jp`.`status` != '3'
GROUP BY `jp`.`id`
ORDER BY `posted_on` DESC
LIMIT 10
I would first suggest not nesting select statements because this will cause an n^x performance hit on every xth level and I see at least 3 levels of selects inside this query.
Add index
INDEX(status, posted_on)
Move LIMIT inside
Then, instead of saying
FROM (`game_post` AS jp)
say
FROM ( SELECT id FROM game_post
WHERE status != 3
ORDER BY posted_on DESC
LIMIT 10 ) AS ids
JOIN game_post AS jp USING(id)
(I am assuming that the PK of jp is (id)?)
That should efficiently use the new index to get the 10 ids needed. Then it will reach back into game_post to get the other columns.
LEFT
Also, don't say LEFT unless you need it. It costs something to generate NULLs that you may not be needing.
Is GROUP BY necessary?
If you remove the GROUP BY, does it show dup ids? The above changes may have eliminated the need.
IN(SELECT) may optimize poorly
Change
AND jrr.referby_user_id IN ( SELECT ab_testing_user_id
FROM ab_testing )
to
AND EXISTS ( SELECT * FROM ab_testing
WHERE ab_testing_user_id = jrr.referby_user_id )
(This change may or may not help, depending on the version you are running.)
More
Please provide EXPLAIN SELECT if you need further assistance.

how to sum amount from two different tables in one query without using union mysql

SELECT SUM(amount_paid) AS total_session FROM session
WHERE session.date = '2016-02-03' AND session.payment_status = 'PAID'
UNION
SELECT SUM(amount_paid) AS total_subscription FROM subscription
WHERE subscription.date_enrolled = '2016-02-03' AND subscription.payment_status = 'PAID'
I just want to display the result in two different columns with alias total_session and total_subscription. How can I do that using union?
Instead of a UNION, put each query as a subquery in a main SELECT
SELECT
(SELECT SUM(amount_paid) FROM session
WHERE session.date = '2016-02-03' AND session.payment_status = 'PAID') AS total_paid,
(SELECT SUM(amount_paid) FROM subscription
WHERE subscription.date_enrolled = '2016-02-03' AND subscription.payment_status = 'PAID') AS total_subscription
In that case, you can try doing a fake join like
SELECT xx.total_session, yy.total_subscription
FROM (
SELECT '1' as ID, SUM(amount_paid) AS total_session FROM session
WHERE session.date = '2016-02-03' AND session.payment_status = 'PAID') xx
JOIN (SELECT '1' as ID, SUM(amount_paid) AS total_subscription FROM subscription
WHERE subscription.date_enrolled = '2016-02-03' AND subscription.payment_status = 'PAID') yy
ON xx.ID = yy.ID;

MySQL SELECT AS

Is there a way out to achieve something as below?
The below query is only to convey the intention. I do understand that it is syntactically incorrect.
SELECT
T_DATE,
T_NAME,
(SELECT MAX(DUR) WHERE STATUS = 'Y') AS UPD_MAX,
(SELECT AVG(DUR) WHERE STATUS = 'Y') AS UPD_AVG,
(SELECT MAX(DUR) WHERE STATUS = 'N') AS READ_MAX,
(SELECT AVG(DUR) WHERE STATUS = 'N') AS READ_AVG
FROM
TABLE_1
WHERE
T_NAME LIKE 'ab%cd%'
GROUP BY
T_DATE,
T_NAME
Use conditional aggregation:
SELECT T_DATE, T_NAME,
MAX(CASE WHEN STATUS = 'Y' THEN DUR END) AS UPD_MAX,
AVG(CASE WHEN STATUS = 'Y' THEN DUR END) AS UPD_AVG,
MAX(CASE WHEN STATUS = 'N' THEN DUR END) AS READ_MAX,
AVG(CASE WHEN STATUS = 'N' THEN DUR END) AS READ_AVG
FROM TABLE_1
WHERE T_NAME LIKE 'ab%cd%'
GROUP BY T_DATE, T_NAME;
try something like that:
SELECT
T_DATE,
T_NAME,
a.UPD_MAX,
c.UPD_AVG,
b.READ_MAX,
d.READ_AVG
FROM TABLE_1
INNER JOIN (SELECT T_NAME, MAX(DUR) AS UPD_MAX FROM TABLE_1 WHERE STATUS = 'Y' GROUP BY T_NAME) as a ON T_NAME=a.T_NAME
INNER JOIN (SELECT T_NAME, MAX(DUR) AS READ_MAX FROM TABLE_1 WHERE STATUS = 'N' GROUP BY T_NAME) as b ON T_NAME=b.T_NAME
INNER JOIN (SELECT T_NAME, AVG(DUR) AS UPD_AVG FROM TABLE_1 WHERE STATUS = 'Y' GROUP BY T_NAME) as c ON T_NAME=c.T_NAME
INNER JOIN (SELECT T_NAME, AVG(DUR) AS READ_AVG FROM TABLE_1 WHERE STATUS = 'N' GROUP BY T_NAME) as d ON T_NAME=d.T_NAME
WHERE T_NAME LIKE 'ab%cd%'
GROUP BY
T_DATE,
T_NAME