How to select static values on mysql select query? - mysql

I am new to mysql, here i am trying to get data from database table.
select id,txnid,amount,status from txn_details;
With above query Getting data successfully but status column getting 0 or 1 or 2, but i want 0 as failed, 1 as success and 2 as not processed.
How to change my query?

You can use a case
select id, txnid, amount,
case when status = 0 then 'failed'
when status = 1 then 'success'
else 'not processed'
end as status
from txn_details;

We can use an expression in the SELECT list. It could be a searched CASE expression e.g.
SELECT CASE t.status
WHEN 0 THEN 'failed'
WHEN 1 THEN 'success'
WHEN 2 THEN 'not processed'
ELSE 'unknown'
END AS status_name
, t.status
, t.amount
, t.txnid
FROM txn_details t
This approach is ANSI-92 standards compliant, and will work in most relational databases.
There are some other MySQL specific alternatives, such as the ELT function ...
SELECT ELT(t.status+1,'failed','success','not processed') AS status_name
, t.status
, t.amount
, t.txnid
FROM txn_details t
https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_elt

If you prefer a central point of maintenance (ie you prefer not to recode all your queries when a new status comes along) you could create a status table and either use a join or sub query to get the values, alternatively you could create a function, for example
drop table if exists txn_details,txn_status;
create table txn_details(id int, txnid int, amount int , status int);
insert into txn_details values
(1,1,10,1),(2,1,10,2),(3,1,10,4);
create table txn_status (id int, statusval varchar(20));
insert into txn_status values
(1,'success'),(2,'not processed'), (3,'failed');
drop function if exists f;
delimiter $$
create function f(instatus int)
returns varchar(20)
begin
declare rval varchar(20);
return (select
case when instatus = 1 then 'success'
when instatus = 2 then 'not processed'
when instatus = 3 then 'failed'
else 'Unknown'
end
);
select t.*,coalesce(ts.statusval,'Unknown') status
from txn_details t
left join txn_status ts on ts.id = t.status;
select t.*,coalesce((select statusval from txn_status ts where ts.id = t.status),'Unknown') status
from txn_details t;
Note the use of coalesce in case a status is not found.
Both produce this result
+------+-------+--------+--------+---------------+
| id | txnid | amount | status | status |
+------+-------+--------+--------+---------------+
| 1 | 1 | 10 | 1 | success |
| 2 | 1 | 10 | 2 | not processed |
| 3 | 1 | 10 | 4 | Unknown |
+------+-------+--------+--------+---------------+
3 rows in set (0.00 sec)
Using the function like this
select t.*, f(status) as status
from txn_details t;
also produces the same result.
Of course using a status table or a function means you have to communicate their availability and enforce their use.
I would also consider the using a foreign key constraint in txn_details to cut down on the number of unknown values and put procedures in place to stop people adding new status codes at will without going through change control

The following query would work. It uses CASE ... END to determine and return values for the virtual column status.
SELECT id,txnid,amount,
CASE
WHEN status = 0 THEN 'failed'
WHEN status = 1 THEN 'success'
WHEN status= 2 THEN 'not processed'
END AS status
FROM txn_details;

Related

Conditional table updates

Consider the following table.
myTable
+----+-----------+------------------------------------+
| Id | responseA | responseB |
+----+-----------+------------------------------------+
| 1 | | {"foo":"bar","lvl2":{"key":"val"}} |
+----+-----------+------------------------------------+
where:
Id, INT (11) PRIMARY
responseA, TEXT utf8_unicode_ci
responseB, TEXT utf8_unicode_ci
Let's say that I want to conditionally update the table with some outside data. The conditions are:
• if there's nothing in responseA, populate it with the outside data, otherwise
• if there is something in responseA, leave it as it is, and populate responseB with the outside data
I was pretty much convinced that I could just do this to get what I want:
UPDATE myTable
SET
responseA = IF(TRIM(responseA) = '','foo',TRIM(responseA)),
responseB = IF(TRIM(responseA) != '','foo',TRIM(responseB))
WHERE Id = 1
However, this updates both responseA and responseB to the same value - foo, making the table:
myTable
+----+-----------+-----------+
| Id | responseA | responseB |
+----+-----------+-----------+
| 1 | foo | foo |
+----+-----------+-----------+
I was expecting my table to look like this after the update:
myTable
+----+-----------+------------------------------------+
| Id | responseA | responseB |
+----+-----------+------------------------------------+
| 1 | foo | {"foo":"bar","lvl2":{"key":"val"}} |
+----+-----------+------------------------------------+
What am I misunderstanding, and how can I achieve this conditional update? Do the updates happen sequentially? If so, I guess that would explain why both of the fields are updated.
UPDATE TABLE
SET responseA = CASE WHEN responseA IS NULL
THEN #data
ELSE responseA
END,
responseB = CASE WHEN responseA IS NULL
THEN responseB
ELSE #data
END
;
here your changed query
UPDATE myTable
SET
responseB = IF(TRIM(responseA) != '','foo',TRIM(responseB)),
responseA = IF(TRIM(responseA) = '','foo',TRIM(responseA))
WHERE Id = 1
It seems the value of responseA is changed before the IF() for responseB is evaluated.
One possible solution is to do a simple UPDATE:
UPDATE mytable SET responseA = ? WHERE id = 1
Then adjust the columns in a trigger, where you have access to both the original and the new value of the columns:
CREATE TRIGGER t BEFORE UPDATE ON mytable
FOR EACH ROW BEGIN
IF TRIM(OLD.responseA) != '' THEN
SET NEW.responseB = NEW.responseA;
SET NEW.responseA = OLD.responseA;
END IF;
END
(I have not tested this.)
I am also assuming that your test for '' (empty string) instead of NULL is deliberate, and that you know that NULL is not the same as ''.
The key point in the UPDATE statement is that you should update first the column responseB, so that column responseA retains its original value which can be checked again when you try to update it:
UPDATE myTable
SET responseB = CASE WHEN TRIM(responseA) = '' THEN responseB ELSE 'foo' END,
responseA = CASE WHEN TRIM(responseA) = '' THEN 'foo' ELSE responseA END
WHERE Id = 1;

Is there a way to restart autoincrement id from 1, when session_id changes? (without using stored procedures ecc..) [duplicate]

I'm working on some legacy code/database, and need to add a field to the database which will record a sequence number related to that (foreign) id.
Example table data (current):
ID ACCOUNT some_other_stuff
1 1 ...
2 1 ...
3 1 ...
4 2 ...
5 2 ...
6 1 ...
I need to add a sequenceid column which increments separately for each account, achieving:
ID ACCOUNT SEQ some_other_stuff
1 1 1 ...
2 1 2 ...
3 1 3 ...
4 2 1 ...
5 2 2 ...
6 1 4 ...
Note that the sequence is related to account.
Is there a way I can achieve this in SQL, or do I resort to a PHP script to do the job for me?
TIA,
Kev
Create a trigger:
CREATE TRIGGER trg_mytable_bi
BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
DECLARE nseq INT;
SELECT COALESCE(MAX(seq), 0) + 1
INTO nseq
FROM mytable
WHERE account = NEW.account;
SET NEW.seq = nseq;
END;
The question is tagged as "mysql", so yes, MySQL's auto_increment can create groupwise sequential ids.
see http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html:
For MyISAM and BDB tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix. This is useful when you want to put data into ordered groups.
edit: example php script (using PDO, but it's the same game with the php-mysql module)
$pdo = new PDO('mysql:host=...;dbname=...', '...', '...');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// example table
$pdo->exec(
'CREATE TEMPORARY TABLE Foo (
id int auto_increment,
account int,
someotherstuff varchar(32),
primary key(account,id)
) engine=MyIsam'
);
// insert example data
$stmt = $pdo->prepare('INSERT INTO Foo (account,someotherstuff) VALUES (?,?)');
$stmt->execute(array(1, '1a'));
$stmt->execute(array(1, '1b'));
$stmt->execute(array(1, '1c'));
$stmt->execute(array(2, '2a'));
$stmt->execute(array(2, '2b'));
$stmt->execute(array(1, '1d'));
unset($stmt);
// query data
foreach( $pdo->query('SELECT account,id,someotherstuff FROM Foo') as $row ) {
echo $row['account'], ' ', $row['id'], ' ', $row['someotherstuff'], "\n";
}
prints
1 1 1a
1 2 1b
1 3 1c
2 1 2a
2 2 2b
1 4 1d
This should work but is probably slow:
CREATE temporary table seq ( id int, seq int);
INSERT INTO seq ( id, seq )
SELECT id,
(SELECT count(*) + 1 FROM test c
WHERE c.id < test.id AND c.account = test.account) as seq
FROM test;
UPDATE test INNER join seq ON test.id = seq.id SET test.seq = seq.seq;
I have called the table 'test'; obviously that needs to be set correctly. You have to use a temporary table because MySQL will not let you use a subselect from the same table you are updating.

SQL user defined function not run

I have situation where I want to generate invoice_id sequential for different product for multiple cities. I want to get generated invoice id according to different product and city.
My table temp look like
id |order_id |product|city|invoice_id
1 | 123 | 1 | 1 | FPU1
2 | 124 | 6 | 1 | PPU1
I want to get next invoice_id for product 1 and city 1 is FPU2.
For product 1 and city 2 is FBN1,product 6 and city 1 is PPU2 and so on ....
I create function but not run.Is anything wrong in function?
CREATE function generate(p_id INT, c_id INT)
returns VARCHAR(50)
BEGIN
-- DECLARE v_new_id VARCHAR(50);
SELECT Concat(( CASE
WHEN t.product = 1 THEN "f"
WHEN t.product = 6 THEN "p" end ),
c.city_name, Cast(RIGHT(t.invoice, Length(t.invoice) - 3) AS UNSIGNED) + 1
) v_new_id
FROM temp AS t
JOIN city c
ON c.city_id = t.city
WHERE t.product = p_id
AND t.city = c_id;
RETURN( v_new_id );
end;
Get syntax error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 15
###Line 15 is AND t.city = c_id;
Need to set delimiters .
Thanks #P.Salmon for valuable comment and link
For set delimiter manually follow
For phpmyadmin user follow this link

MySql whole query returns Error 1690 while parts of it doesn't

I know that Error 1690 is nothing new in mysql but after searching for solution here i just gave up. So here I go, the error I get is:
BIGINT UNSIGNED value is out of range in '(v_from#10 - p_from#1)'
The problem is, I do not have any substraction in my query... honestly i even removed "-" from DATE_FORMAT!
My query is:
SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';
select count(distinct user_id) as 'event_count_dis',count(user_id) as 'event_count',DATE_FORMAT(event_time,'%Y%m') as 'data',
getEventCourse(event_desc) as 'Name'
from sys_events c where DATE_FORMAT(event_time,'%Y%m') like '201809'
and event_type in ('Clicked')
group by getEventCourse(event_desc)
order by count(distinct user_id) desc Limit 20
Function getEventCourse(event_desc) works perfectly as it is very simple.
When i dissect this query and tested every part of it separately, everything worked fine... and I just gave up... Maybe some of you have any idea what's wrong? or at least can tell me what the heck is
'(v_from#10 - p_from#1)'
Function getEventCourse:
BEGIN
DECLARE courseName varchar(100);
IF(LOCATE('cid',description) > 0) THEN
SET courseName = (Select courses_name from sys_courses where courses_id = test_baza.extract_json_value(description,'cid'));
ELSEIF(LOCATE('course_id',description) > 0) THEN
SET courseName = (Select courses_name from sys_courses where courses_id = test_baza.extract_json_value(description,'course_id'));
ELSE
SET courseName = null;
END IF;
RETURN courseName;
END
sys_events:
event_id | event_time | event_desc | event_type | user_id
1537919 | 2018-10-12 | {"course_id":"386","element_id":"498"}| Clicked | 1235
Edit:
Ok, it seems that problem appears in "group by" section.

How to analyze, what happend while updating rows

I have a table like this:
| id | address | name | oid | state | event_id | ctrl |
-------------------------------------------------------------------
| 1 | test_addr_1 | test_1 | 25.345.17 | 1 | 0 | 15 |
I need to get event_id while update data in row.
I want to do something like this:
If new name not equals with old name event_id = event_id + 1
If new oid not equals with old oid event_id = event_id + 2
If new state not equals with old state event_id = event_id + 4
If new ctrl bigger then old ctrl event_id = event_id + 8
# Params to procedure
PROCEDURE Write(IN pAddr VARCHAR(20), IN pName VARCHAR(20), IN pOid VARCHAR(20), IN pState TINYINT, IN pCtrl INT)
#procedure body
SET #ev = 0;
SELECT
CASE
WHEN name != pName THEN SET #ev = #ev + 1
WHEN oid != pOid THEN SET #ev = #ev + 2
WHEN state != pState THEN SET #ev = #ev + 4
WHEN ctrl > pCtrl THEN SET #ev = #ev + 8
END
FROM table1
UPDATE table1 SET ..... , event_id = #ev WHERE address = pAddr
How can I do it? Or will it be better to make it not with the help of SQL?
As already suggested, an audit trigger can be used here to ensure that changes from all sources are caught. However, I suggest two changes:
1) audit tables - use other tables to hold audit data, as these tables tend to grow and it is not recommended to mix operational and auditing data in the same structures (even in the same database)
2) use more friendly change flag - from your example, it seems that you are setting bits in an integer value. While this provides compact data (catch many changes within a single integer), it requires more convoluted operations to see when the name has changed for example. The audit table can simply have BIT(1) columns like nameChanged, oidChanged etc.
CREATE TRIGGER table1Audit BEFORE UPDATE ON <table1>
FOR EACH ROW BEGIN
SET #ev =
(CASE WHEN OLD.name != NEW.name THEN 1 ELSE 0 END) +
(CASE WHEN OLD.oid != NEW.oid THEN 2 ELSE 0 END) +
(CASE WHEN OLD.state != NEW.state THEN 4 ELSE 0 END) +
(CASE WHEN OLD.ctrl != NEW.ctrl THEN 8 ELSE 0 END)
-- INSERT INTO someaudittable
--'table1', #ev
END;
Solved! Thanks to #Alexei.
I wanted to know, why the row was added to the history table.
The result is:
CREATE TRIGGER SetReason BEFORE UPDATE ON <table1>
FOR EACH ROW BEGIN
SET NEW.event_id =
(CASE WHEN OLD.name != NEW.name THEN 1 ELSE 0 END) +
(CASE WHEN OLD.oid != NEW.oid THEN 2 ELSE 0 END) +
(CASE WHEN OLD.state != NEW.state THEN 4 ELSE 0 END) +
(CASE WHEN OLD.ctrl != NEW.ctrl THEN 8 ELSE 0 END)
END;