I have a problem order by column name(String) when i have more than one word, like " Kafka Streams" and "Kafka Connectors". The order should be "Kafka Connectors", "Kafka Streams" but it order "Kafka Streams" ,"Kafka Connectors". The first word is ok, but second not. How can i resolve this?
I tried use substring and charindex, but the last one dont work in sequelize RAW queries.
sequelize.query(
'SELECT `technology`.`business_unit_id`, `technology`.`unit_reference_data_technology_id`' +
'FROM `unit_reference_data_technology` AS `technology`' +
'WHERE (`technology`.`description` LIKE (:name) ') ' +
'ORDER BY `technology`.`description` ASC, LIMIT ' + limit + ' OFFSET ' + offset + '', { model: Models.unit_reference_data_technology, mapToModel: true, replacements: { business_unit_id, name: '%' + text + '%', limit: 10,}, type: sequelize.QueryTypes.SELECT })
Example
I m using MySQL and a Sequelize (nodeJS).
Can anyone help me? My solution is ORDER BY first word ASC, second word ASC ( If the string have always 2 words)
Related
I am trying to get letters before numbers with a descending order and am finding it very difficult to do so.
I have tried using Case ordering
ORDER BY CASE WHEN ' . $this->sortbycast . ' LIKE \'%[a-z]%\' THEN 0 WHEN ' . $this->sortbycast . ' LIKE \'%[0-9]%\' THEN 1 ELSE ' . $this->sortbycast . ' END DESC
Regular expression as follows
' ORDER BY ' . $this->sortbycast . ' REGEXP \'^[a-z]\', ' . $this->sortbycast . ' desc';
and CAST()
' ORDER BY CAST(' . $this->sortbycast . ' AS UNSIGNED), ' . $this->sortbycast;
But none of these have had the desired result. All work correctly with ascending order. Any help would be appreciated. Thanks.
Update due to Strawberry's response
DB Fiddle here
My present query looks like this - reformatted for legibility:
SELECT p.*
, m.data
, m.id author_id
FROM anchor_posts p
JOIN anchor_post_meta m
ON m.post = p.id
WHERE p.category = 5
AND m.extend = 3
ORDER
BY CAST('anchor_post_meta.data' AS UNSIGNED) -- NOTE: THIS IS A STRING !?!
, m.data DESC
LIMIT 12;
The desired result
The desired result would be to have items show in the following order:
data
==============
A Title
B Title
C Title
D Title
70000
60000
45000
30000
25000
12000
Please see the following version of the DB Fiddle to see more clearly.
Currently, I am using string manipulation for passing value for multiple where clause.
Since docs for raw queries with replacements does not support multiple where clause and i cannot use simply use a find()
Since my requirement needs complex mysql queries which is not possible using find().
Is there any way of accomplish this basic task for multiple filtration in "Raw queries mode" ?
if(selector==""){
selector="where "+searchkey+" LIKE "+"'%"+searchvalue+"%'";
}
else
{
selector=selector+" and "+searchkey+' LIKE %' + searchvalue + '%';
}
sequelize.query('select ROLEID as RoleID,Rolename, CASE WHEN isactive = 1 THEN \'True\' ELSE \'False\' END as isactive , ' +
'GROUP_CONCAT(DISTINCT modID) ModID,' +
'GROUP_CONCAT(DISTINCT Modulename) Modulename,' +
'GROUP_CONCAT(DISTINCT Accestype) Accestype ' +
'from ' +
'( ' +
'select isactive,rl.roleid AS ROLEID,n.modnameID as modID, n.Mname as Modulename,rl.rolename as Rolename, r.Accestype as Accestype from mrole r ' +
'left join modname n ' +
'on r.modulename=n.modnameID ' +
'left join role rl ' +
'on rl.roleid=r.rolename '+
') as a '+selector+' GROUP BY ROLEID,Rolename,isactive '+
'limit :NUMBER_OF_ITEMS ' +
'offset :PAGE_NUMBER ', {
replacements: {
NUMBER_OF_ITEMS: parseInt(NUMBER_OF_ITEMS),
PAGE_NUMBER: parseInt(PAGE_NUMBER)
},
type: sequelize.QueryTypes.SELECT
}
).then(function(projects) {
var red = new Object();
red.rows = projects;
res.json(red);
})
I want to make the ORDER BY dynamic in mysql query in node.js. But it's not working. I console.log the multiQuery variable and everything looks perfect but when ran it simply doesn't work. This is what I have:
var order,
multiQuery;
if(req.query.o){
order = req.query.o;
}else{
order = "views";
}
multiQuery = 'SELECT COUNT(Category) AS Count FROM posts;';
//PROBLEM LIES HERE IN THE SECOND ONE
multiQuery += 'SELECT ID, Title, Img_path, Category, Views FROM posts WHERE Category = ' + connection.escape(category) + ' ORDER BY' + connection.escape(order) + 'DESC LIMIT ' + start_from + ', 15;';
connection.query(multiQuery, function(err, result){
});
This does not work:
SELECT foo FROM bar ORDER BY 'baz';
This does work :
SELECT foo FROM bar ORDER BY baz;
Did you try removing the quotes that connection.escape adds?
Try using this:
function escapeSansQuotes(connection, criterion) {
return connection.escape(criterion).match(/^'(\w+)'$/)[1];
}
then use escapeSansQuotes(connection, order) instead of connection.escape(order).
try using a proper spacing for each token
//PROBLEM LIES HERE IN THE SECOND ONE
multiQuery += 'SELECT ID, Title, Img_path, Category, Views
FROM posts WHERE Category = ' + connection.escape(category) +
' ORDER BY ' + connection.escape(order) +
' DESC LIMIT ' + start_from + ', 15;';
Check if you did enabled the multi-query into your connection object.
http://nickolayconsulting.com/node-js-and-multiple-sql-calls-in-one-query/
Support for multiple statements are disabled by default for security
reasons (it allows for SQL injection attacks if values are not
properly escaped). To use this feature you have to enable it for your
connection:
var connection = mysql.createConnection({multipleStatements: true});
I have a normal SQL statement:
SELECT VALUE_ID, UF_CRM_TASK FROM b_uts_tasks_task
Now this returns a a different field everytime but they take the form of the following:
a:1:{i:0;s:7:"CO_2012";} or a:1:{i:0;s:5:"CO_12";} or a:1:{i:0;s:7:"CO_2017";}
Basically they're different everytime. What I need is to just get the number after the CO_ part. I have tried TRIM but because everything changes in the leading and trailing section I don't think this would work.
I have looked on Stack Overflow for a while and cannot find it. I know how to do it in PHP:
$data = $row['UF_CRM_TASK'];
$companyID = substr($data, strpos($data, "CO_") + 1);
$newCompanyID = preg_replace('/[^0-9.]+/', '', $companyID);
But not SQL. Thanks in advance
In MYSQL is a bit ugly:
/*SUBSTRING_INDEX BASED ON CO_ AND THE LAST " - in 2 SUBSTRINGS*/
SELECT `VALUE_ID`, SUBSTRING_INDEX(SUBSTRING_INDEX(`UF_CRM_TASK`, 'CO_', -1), '"', 1) AS `COMPANY_ID` FROM `b_uts_tasks_task`
In PHP you can just unserialize():
$data = unserialize($row['UF_CRM_TASK']);
$companyID = str_replace('CO_', '', $data[0]);
eg:
$data = unserialize('a:1:{i:0;s:5:"CO_12";}');
echo str_replace('CO_', '', $data[0]);
//==> 12
You need to use CharIndex and SubString (Microsoft SQL) or
This is the sample code I made for my Microsoft SQL server:
declare #companyIdString varchar(50) = 'a:1:{i:0;s:7:"CO_2012";}'
print 'Company ID in a string: ' + #companyIdString
print 'Find first position: ' + Cast(charindex('"CO_', #companyIdString) as varchar(2))
print 'Locate the second position (the last "): ' + Cast(charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) as varchar(2))
print 'Extracted Company Id: ' + substring(#companyIdString,charindex('"CO_', #companyIdString)+4, charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) - charindex('"CO_', #companyIdString) - 4)
select
#companyIdString as CompanyIdString,
substring(#companyIdString,charindex('"CO_', #companyIdString)+4, charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) - charindex('"CO_', #companyIdString) - 4) as CompanyId
I also made the same code on a mySQL server:
set #companyIdString := 'a:1:{i:0;s:7:"CO_2012";}';
select
#companyIdString as CompanyIdString,
substring_index(substring_index(substring_index(#companyIdString, '"', 2), '"', -1), '_', -1) as CompanyId
The substring_index starts by locating the second " (string is now a:1:{i:0;s:7:"CO_2012), then it searches backward with the -1 to locate the first " (string is now CO_2012). And then it searches backward for the underscore (string is now 2012).
hey guys,
i have a query in sql server which takes atleast 10-15 seconds to execute, and when this is called in asp.net, it is more worst there, it just throws request timeout error.
Below is the query i am using.
SELECT C.Id,
C.Summary,
C.Title,
C.Author,
CONVERT(VARCHAR(12), C.PublishDate, 104)
AS 'DATE',
'/Article/' + SUBSTRING(dbo.RemoveSpecialChars(C.Title), 0, 10) + '/' + CAST(CA.CategoryId AS VARCHAR(MAX)) + '/' + CAST(C.Id AS VARCHAR(MAX)) +
'.aspx' AS
'URL'
FROM CrossArticle_Article C
INNER JOIN CrossArticle_ArticleToCategory CA
ON C.Id = CA.ArticleId
WHERE C.Title LIKE '%' + #KEYWORD + '%'
OR C.Summary LIKE '%' + #KEYWORD + '%'
OR C.Article LIKE '%' + #KEYWORD + '%'
SELECT ##ROWCOUNT
Below are the Fields Specification.
Id int Primary Key
Summary nvarchar(1000)
Title nvarchar(200)
Author nvarchar(200)
PublishDate DateTime
CategoryId int PrimaryKey
i think this can be resolved by using Indexing on these columns using include.. i checked over net, but didnt find any solution..
i would appreciate if i could get help for the same.
Thanks and Regards
Abbas Electricwala
Ordinary column indexing most likely cannot help your query, unfortunately. LIKE conditions can only be assisted by indexes when they are in the form of value% (meaning that you can only have a wildcard on the end of the expression; the prefix must be static).
I am assuming that you already have an index on CrossArticle_Article.Id and CrossArticle_ArticleToCategory.ArticleId. If not, you should add those.