Trouble with a MySQL-Query - mysql

When I try to execute this query I got trouble.
INSERT INTO af_pres (cod,pres,fecha,tipo,stad,oper,ref,monto)
VALUES
("",
(CASE
(SELECT p.pres FROM af_pres p WHERE
p.pres LIKE "%0100000100191000140100%" AND
p.fecha LIKE "%2014%" = ''
THEN pres ELSE
(pres = "2014"))END),
"2014-09-26","G","1","M","MOD-2014",70000);

You can not use SELECT in CASE as you are doing in your query. MySQL does not have this feature built in.
If you describe what you want to do, we can help you more.
Ok here is a solution, but I have not tried it :)
INSERT INTO af_pres (cod,pres,fecha,tipo,stad,oper,ref,monto)
VALUES
("",
(SELECT IF (COUNT(p.pres) > 0, pres, '2014')
FROM af_pres p
WHERE p.pres LIKE "%0100000100191000140100%"
AND p.fecha LIKE "%2014%" = ''),
"2014-09-26",
"G",
"1",
"M",
"MOD-2014",
70000);

Related

How to query multiplte row in one json object

table provider
table provider_properties
here I wanted the result something like
{
"provider_uuid": "b897f790-ee90-4869-9345-690380b1a0c9",
"name": "Provider 1",
"password": "112233",
"username": "provider_1",
"properties": {
"address_1": "Dubai",
"address_2": "NY"
}
}
here i tried something like
SELECT provider.*, json_object(provider_properties.key_name, provider_properties.key_value) as properties FROM provider JOIN provider_properties on provider.provider_id = provider_properties.provider_uuid;
but the problem is i am getting 2 rows
Since your expected results need specific formatting in json. You want to refer to JSON Formatted output. This is for shell though.
You might also want to try this...
This would give you a tabular results but in one row.
SELECT
provider.*,
p_props.properties
FROM provider
JOIN (
provider_uuid,
SELECT JSON_OBJECTAGG(
provider_properties.key_name,
provider_properties.key_value
) as properties
FROM provider_properties
GROUP BY provider_uuid
) p_props ON provider.provider_id = p_props.provider_uuid;
CONCAT() and REPLACE() here are used for sorting the order of columns.
I would say the use of REPLACE() here is quite risky, please test it out and see how it goes.
db<>fiddle
SELECT
p.*,
CONCAT(
'{"', 'provider_uuid": "', pp.provider_uuid, '"',
REPLACE(JSON_OBJECT('name', p.name, 'password', p.password,
'username', p.username, 'properties', pp.name_value), '{"name', ', "name')
) AS your_json
FROM provider p
JOIN (
SELECT provider_uuid, JSON_OBJECTAGG(key_name, key_value) as name_value
FROM provider_properties
GROUP BY provider_uuid
) pp ON p.provider_id = pp.provider_uuid;

Sequelize returns different value than MySql result

I have something very odd happening and nothing seems to work. I have a SP in MySql that returns some results. When I run the SP in MySql workbench everything is correct. The query is quite long. But this is the LEFT JOIN is somehow creating the issues. I have other inner joins/left joins but they are fine.
SELECT DISTINCT Id.ReelTag
, Id.ECSPartNo
, WM.ShortDescription AS Description
, Id.ReelTagSerial
, group_concat(DISTINCT RA.UniqueID) AS UniqueID
, group_concat(DISTINCT coalesce(RA.OrdNo, Std.OrdNo)) AS OrdNo
, Id.Received
, IFNULL(Std.ReelQuantity,0) AS OriginalQuantity
, IFNULL(Id.Quantity,0) AS CurrentQuantity
, IFNULL(yest.Quantity,0) AS YesterdayQuantity
, IFNULL(cuts.Quantity,0) AS QuantityChanged
, cuts.OrdNo AS OrdNoChange
, IFNULL(CC.ShipQuantity,0) AS ShipQuantity
, CC.OrdNo AS OrdNo_Allocated
, IFNULL(Id.Quantity,0) - IFNULL(yest.Quantity,0) AS changeAOF_Yesterday
FROM InventoryDtl Id .....
LEFT JOIN (
SELECT
SourceReel
, SUM(CASE WHEN Action = 'Insert' THEN TotalQuantity
WHEN Action = 'Delete' THEN -TotalQuantity
ELSE 0 END) AS Quantity
, group_concat(DISTINCT CASE WHEN Action = 'Insert' THEN concat(OrdNo,'(Cut)') ELSE concat(OrdNo,'(UnCut)') END) AS OrdNo
FROM (
SELECT
Action
, SourceReel
, OrdNo
, SUM(Quantity) AS TotalQuantity
FROM CableCuts_Log CD
WHERE 1=1
AND 1 = CASE
WHEN SourceReel IS NOT NULL AND OrdNo LIKE 'E9%' AND Quantity > 0 AND DaTediff(Now(),LogDate) = 0 THEN 1
ELSE 0 END
GROUP BY Action, SourceReel, OrdNo
) CC
WHERE 1=1
GROUP BY SourceReel
) cuts ON Id.ReelTag = cuts.SourceReel
Again, When I run this in MySql workbench it's fine and loads in a second if that makes a difference.
But when I call my API to call the SP using ...
let inventoryReport = await models.sequelize
.query(
`call rpt_DailyInventoryReport($location, $byECSPartNo);`,
{ bind: {location: req.body.location, byECSPartNo: null} },
)
for(i=0;i<inventoryReport.length;i++) {
if(inventoryReport[i].ReelTagSerial == '6906' || inventoryReport[i].ReelTagSerial == '6858') {
console.log(inventoryReport[i]);
}
}
and exporting that into an Excel using ExcelJS, the 2 "cuts" columns from the query are essentially NULLs, because the return value of the "cuts" select are coming up NULLS, which is why it's giving the IFNULL value instead. Again this work in MySql workbench.
These are the values the API throws out.
{
"ReelTagSerial": 6858,
"CurrentQuantity": 700,
"YesterdayQuantity": 2500,
"QuantityChanged": 0,
"OrdNoChange": null,
"ShipQuantity": 0,
"OrdNo_Allocated": null,
"changeAOF_Yesterday": -1800
},
{
"ReelTagSerial": 6906,
"CurrentQuantity": 2730,
"YesterdayQuantity": 3330,
"QuantityChanged": 0,
"OrdNoChange": null,
"ShipQuantity": 0,
"OrdNo_Allocated": null,
"changeAOF_Yesterday": -600
},
Here are the 2 rows that their values should be.
{
"ReelTagSerial": 6906,
"CurrentQuantity": 2730,
"YesterdayQuantity": 3330,
"QuantityChanged": 600,
"OrdNoChange": E92021(Cut),
"ShipQuantity": 0,
"OrdNo_Allocated": null,
"changeAOF_Yesterday": -600
}
{
"ReelTagSerial": 6858,
"CurrentQuantity": 700,
"YesterdayQuantity": 2500,
"QuantityChanged": 1800,
"OrdNoChange": E912345(Cut),
"ShipQuantity": 0,
"OrdNo_Allocated": null,
"changeAOF_Yesterday": -1800
},
I have tried creating a temp table and defining the field type of varchar, text, mediumint for the QuantityChanged field.
At first I thought maybe ExcelJs was not liking the key/value pairs but then I simply console logged the 2 rows and they are returning like that from Sequelize. I have tried casting the 2 fields with every datatype possible.
, CAST(cuts.OrdNo AS char) AS OrdNoChange
, CAST(cuts.OrdNo AS binary) AS OrdNoChange
Now I am just immediately sending the return result as a response back to Postman and seeing all the rows to make sure for whatever reason those values are not being set in other rows. But they seem to be all good.
If I simply rearrange the columns so that the two bad fields get values of other fields, they do populate with their values, so that's about as far as I got. Or if I put just 1000 or a string type it returns correctly, so IT MUST be something to do with those 2 data types from the "cuts" query.
I have tried returning simply returning these from the "cuts" join query
SELECT
DISTINCT SourceReel
#, CAST(SUM(CASE WHEN Action = 'Insert' THEN TotalQuantity
# WHEN Action = 'Delete' THEN -TotalQuantity
# ELSE 0 END) AS UnSigned) AS Quantity
, SUM(TotalQuantity) AS Quantity
, OrdNo
#, group_concat(DISTINCT CASE WHEN Action = 'Insert' THEN concat(OrdNo,'(Cut)') ELSE concat(OrdNo,'(UnCut)') END) AS OrdNo
Nothing is working. Spent hours troubleshooting and searching...
Need some help please :)
Thanks in advance.
I was able to get around this by creating a table and inserting into it during the SP call. Then in NodeJs I created a model of that table and just used to find everything in the table immediately after I called the SP.
let inventoryReport = await models.Rpt_DailyInventory_Temp.findAll();
Then just TRUNCATE the table every time the SP is called.

MySQL CONCAT values on SELF JOIN

l'm working on a query for an ajax auto suggestion feature on my website and need a little help.
I'm using the following query:
SELECT
CONCAT(b.cat_name, ' > ', a.cat_name) as value,
a.cat_id as data
FROM categories a
LEFT JOIN categories b
ON b.cat_id = a.cat_parent_id
WHERE a.cat_path LIKE '%health%' OR a.cat_slug LIKE '%health%' OR a.cat_name LIKE '%health%' OR a.cat_legacy_path LIKE '%health%'
ORDER BY a.cat_path ASC LIMIT 500
The problem is coming up with root categories where parent_cat_id IS NULL
I'd still like them to appear in my results however as it stands now, the results are coming back empty for the root categories.
Can someone help me tweak this query so that l can accomplish what l'm looking to do?
If it makes any difference l'm doing this with CodeIgniter 3, so here's the actual active record code l'm using on the query:
$search_term = strtolower($search_term);
$this->db->select("CONCAT(b.cat_name, ' > ', a.cat_name) as value, a.cat_id as data");
$this->db->from('categories a');
$this->db->like('a.cat_path', $search_term, 'both', false);
$this->db->or_like('a.cat_slug', $search_term, 'both', false);
$this->db->or_like('a.cat_name', $search_term, 'both', false);
$this->db->or_like('a.cat_legacy_path', $search_term, 'both', false);
$this->db->join('categories b', 'b.cat_id = a.cat_parent_id', 'left');
$this->db->order_by("a.cat_path", 'ASC');
$this->db->limit('500');
$query = $this->db->get();
Ideally l'd like the root categories (where cat_parent_id IS NULL) to just be selected as a.cat_name as value as apposed to CONCAT(b.cat_name, ' > ', a.cat_name) as value.
Any help would be greatly appreciated.
You just need to make it conditional:
SELECT
COALECSE(CONCAT(b.cat_name, ' > ', a.cat_name), a.cat_name) as value,
or, checking more precisely for this exact cause of NULL,
SELECT
IF(a.cat_parent_id IS NULL, a.cat_name, CONCAT(b.cat_name, ' > ', a.cat_name)) as value,
So in your case in codeigniter that would translate to something like:
$this->db->select("COALECSE(CONCAT(b.cat_name, ' > ', a.cat_name), a.cat_name) as value, a.cat_id as data");

Adding a comment to last column of query but not updating it in database

*** SOLUTION IN BOTTOM****
I am trying to add some comment at last column of my query , basically if technical_document.disc_id contains "KN" then i want to add a comment to the last column of query 'OK'
but i cant get it working
SELECT
technical_document.project_no,
technical_document.doc_no,
technical_document.doc_class,
technical_document.disc_id,
tag_document.project_id AS "COMMENT"
CASE WHEN technical_document.disc_id = 'KN' THEN tag_document.project_id = "YES"
FROM technical_document left join tag_document on technical_document.doc_no = tag_document.proj_doc_doc_no
WHERE tag_document.proj_doc_doc_no IS NULL
AND technical_document.project_no like '%%'
AND technical_document.doc_class = ANY ('A','S','SE')
AND technical_document.Lci_Code = ANY ('A','A1','B')
Thanks for your help, here is how it was solved, sorry for confusing/misleading explanation on my part:
SELECT
technical_document.project_no,
technical_document.doc_no,
technical_document.doc_class,
technical_document.disc_id,
CASE
WHEN technical_document.disc_id LIKE 'KN' THEN 'OK'
WHEN technical_document.disc_id LIKE 'K6' THEN 'OK'
ELSE null
END
FROM technical_document left join tag_document on technical_document.doc_no = tag_document.proj_doc_doc_no
WHERE tag_document.proj_doc_doc_no IS NULL
AND technical_document.project_no like '%%'
AND technical_document.doc_class = ANY ('A','S','SE')
AND technical_document.Lci_Code = ANY ('A','A1','B')
I would write the query as:
SELECT d.project_no, d.doc_no, d.doc_class, d.disc_id,
d.project_id AS COMMENT,
(CASE WHEN td.disc_id = 'KN' THEN td.project_id = 'YES' END)
FROM technical_document d LEFT JOIN
tag_document td
ON d.doc_no = td.proj_doc_doc_no
WHERE d.proj_doc_doc_no IS NULL AND
d.project_no like '%%' AND -- not needed
d.doc_class IN ('A', 'S', 'SE') AND
d.Lci_Code IN ('A', 'A1', 'B');
First, you have a WHERE clause that says that there is no match. Hence, including columns in the SELECT from tag_document doesn't make sense. I suspect you intend:
SELECT d.project_no, d.doc_no, d.doc_class, d.disc_id,
d.project_id as COMMENT,
(CASE WHEN td.disc_id = 'KN' THEN td.project_id = 'YES' END)
FROM technical_document d LEFT JOIN
tag_document td
ON d.doc_no = td.proj_doc_doc_no AND td.disc_id = 'KN'
WHERE d.project_no like '%%' AND -- not needed
d.doc_class IN ('A', 'S', 'SE') AND
d.Lci_Code IN ('A', 'A1', 'B');
Note the condition on td in the WHERE clause has been removed.
In addition:
Table aliases make the query easier to write and to read.
= ANY is allowed, but the colloquial operator is IN.
Various small syntax errors are fixed -- missing commas, missing END.

MySql Remove All Substrings that Match Table Values

I have a VARCHAR variable and I would like to remove all substrings that match a column in a table. So far I have built a query that will return all rows that are a substring of my variable, using the following query:
SET #myval = '%For Her, Shoes,, Sizes 14-24%';
SELECT strReplace
FROM tbl_StringsToReplace
WHERE #myval LIKE CONCAT('%', strReplace, '%');
But I am having trouble writing a REPLACE query that will replace multiple values. I am trying to write something like the following:
SET #myval = REPLACE((SELECT strReplace
FROM tbl_StringsToReplace
WHERE #myval LIKE CONCAT('%', strReplace, '%')), '', #myval);
But I am getting the error:
Error Code: 1242. Subquery returns more than 1 row
I would love to achieve this in pure SQL. Euther way, any advice would be greatly appreciated. Thanks
Try:
SET #myval = '%For Her, Shoes,, Sizes 14-24%';
select val into #myval
from (
SELECT #myval := replace(#myval, strReplace, '') val
FROM tbl_StringsToReplace
) r
order by length(val)
limit 1;
select #myval;