how to alias(AS) a table in raw SQL with knex.js - mysql

I am using knex.js with MySql DB. I have a migration where I have to use raw SQL. My migration looks like this :
import * as Knex from "knex";
const brokersTable = "OriginationAdmin.Brokers";
const brokerIndividualTable = "OriginationAdmin.BrokerIndividuals";
exports.up = async (knex: Knex) => {
await knex.schema.raw(
`UPDATE ${brokersTable}
JOIN(
SELECT CompanyName, MIN(Id) AS Id
FROM ${brokersTable}
GROUP BY CompanyName )
AS x
ON x.CompanyName = ${brokersTable}.CompanyName
AND isDeleted IS NULL
SET isDeleted = CASE WHEN (x.Id <> ${brokersTable}.Id) THEN 1 END`
);
when I run migrate up I get an error message:RequestError: Incorrect syntax near the keyword 'AS'. I know the SQL Query is syntactically correct but why am I getting an error with the aliasing keyword and how do I fix it?
Edit: This most(relevant part) of the error message
migration file "20210822190619_de-duplicate-brokers-and-associate-individuals.ts" failed
migration failed with error: UPDATE OriginationAdmin.Brokers
JOIN (
SELECT CompanyName, MIN(Id) AS Id
FROM OriginationAdmin.Brokers
GROUP BY CompanyName
) AS x
ON x.CompanyName = OriginationAdmin.Brokers.CompanyName
AND isDeleted IS NULL
SET isDeleted = CASE WHEN (x.Id <> OriginationAdmin.Brokers.Id) THEN 1 END
- Incorrect syntax near the keyword 'AS'.
RequestError: Incorrect syntax near the keyword 'AS'.
at handleError (/Users/haroonAzhar/Desktop/FAL/omni-api/node_modules/mssql/lib/tedious/request.js:366:15)
The error message isn't very helpful to what the problem is.

Related

use sql SELECT nodejs

I tried to use the select sql option in node js sql plugins.
But I get a error with this syntax :
con.query( 'SELECT token FROM utilisateursinvitation WHERE nomwork = ? AND
Rejoint = ? EXCEPT SELECT token FROM utilisateursinvitation WHERE nomwork
= ? AND Rejoint = ? AND nomdugroupe = ? ',
[nomwork,tatazueyzyu,"nomdugroupe"], function (error, results, fields) {
and the error :
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'EXCEPT SELECT token FROM utilisateursinvitation WHERE nomwork = 'nomdugroupe' ' at line 1
Because I don't know the correct syntax.
Can you help me ? THanks!
EXCEPT is not MySQL syntax.
Instead, you can use NOT IN or NOT EXISTS:
SELECT ui.token
FROM ui.utilisateursinvitation ui
WHERE ui.nomwork = ? AND ui.Rejoint = ? AND
NOT EXISTS (SELECT
FROM utilisateursinvitation ui2
WHERE ui2.token = ui.token AND
ui2.nomwork = ? AND ui2.Rejoint = ? AND
nomdugroupe = ?
);
Or, if you are trying to fine tokens that have nomwork and Rejoint as the input values, but not a particular nomdugroupe:
SELECT ui.token
FROM ui.utilisateursinvitation ui
WHERE ui.nomwork = ? AND ui.Rejoint = ?
GROUP BY ui.token
HAVING SUM(nomdugroupe = ?) > 0;

SQL nested queries and subqueries

i've been having an error with this query and i'm not sure how to fix it. this query is supposed to filter occupations stored in my database to match the volunteer's occupation. please help me fix my query. all the names in this query are correctly spelled, i double checked all the spellings before writing the query here.
the error says "#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT (SELECT count(*) FROM occupation_event WHERE event_id='8' AND occupationN' at line 1"
SELECT
*
FROM
volunteer_details
WHERE
user_id=73
AND
volunteer_occupation in (
SELECT
occupationName
FROM
occupation_event
WHERE
event_id=8
OR SELECT (
SELECT
count(*)
FROM
occupation_event
WHERE
event_id='8'
AND
occupationName = 'No Occupation Required') > 0 AS need
)
I think the error is the as need at the end. I would write this as:
SELECT vd.*
FROM volunteer_details vd
WHERE user_id = 73 AND
(vd.volunteer_occupation in (SELECT oe.occupationName FROM occupation_event oe WHERE oe event_id = 8) or
exists (select 1 from occupation_event oe where event_id = 8 and oe.occupationName = 'No Occupation Required')
);

Update table using GUID

I am using MySQL with ASP.NET/VB. In a table I use GUID instead of int identifiers. All goes as planned until I try to update a specific row, where I get a syntax error in the statement below:
Dim q As String = "UPDATE documents SET date_document = #date_document, document_type = #document_type, sender = #sender, receiver = #receiver, description = #description, document_number = #document_number, pages = #pages, handled_date = current_timestamp, handled_user_id = #handled_user_id, error_code = #error_code) WHERE id = #id"
My GUID parameter:
.Parameters.Add("#id", MySqlDbType.Guid, 16).Value = myguid
And the error:
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 ') WHERE id = '8873442f-2f0b-4372-ac08-8388220c6eca'' at line 1
Any ideas on what's going on?
You're chasing down the wrong issue. What character does your error syntax begin with? It starts off as ') Where id = ...
You're assuming it's the id. It's not. That works fine. The first character is a closing parenthesis. That's the clue. There is no opening parenthesis. Remove the ) because you don't need it with an update statement.

Sql error occurred when I'm trying this query

Here is the query
$query_order = "select * from orders where key = '$pay_key'";
Error shown
SELECT
*
FROM `orders`
where `key` = 'C90320'
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 'key = 'C90320'' at line 1*
key is a reserved word. Change your query to:
$query_order = "select * from orders where `key` = '$pay_key'";
Also, I would recommend escaping the $pay_key's value. Say something like:
$pay_key = mysqli_real_escape_string($pay_key);
$query_order = "select * from orders
where `key` = '".mysqli_real_escape_string($pay_key)."'";
try this
first of all you need to compare it using string so code should like this
$query_order = "select * from orders where `key` = '".$pay_key."'";

arel union and latest conversation from messages

I need a list of messages where each one is the most recent in the "conversation" between the current user and each other user.
The same query is described in this question
The code I have so far is:
t1 = Arel::Table.new(:messages, :as => 't1')
t2 = Arel::Table.new(:messages, :as => 't2')
convs1 = t1.
project(
t1[:receiver_user_id].as('other_user_id'),
t1[:receiver_user_id].as('receiver_user_id'),
t1[:sender_user_id].as('sender_user_id'),
t1[:created_at].as('created_at')
).
where(t1[:sender_user_id].eq(user.id))
convs2 = t2.project(
t2[:sender_user_id].as('other_user_id'),
t2[:receiver_user_id].as('receiver_user_id'),
t2[:sender_user_id].as('sender_user_id'),
t2[:created_at].as('created_at')
).
where(t2[:receiver_user_id].eq(user.id))
conv = convs1.union(convs2)
First off, I get an error:
ActiveRecord::StatementInvalid: Mysql2::Error: 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 \
'UNION SELECT `t2`...
This works if I manually replace "UNION" with "UNION ALL" in the sql produced below.
conv.to_sql from the above code produces:
SELECT `t1`.`receiver_user_id` AS other_user_id,
`t1`.`receiver_user_id` AS receiver_user_id, `
t1`.`sender_user_id` AS sender_user_id,
`t1`.`created_at` AS created_at
FROM `messages` `t1`
WHERE `t1`.`sender_user_id` = 50
UNION
SELECT `t2`.`sender_user_id` AS other_user_id,
`t2`.`receiver_user_id` AS receiver_user_id,
`t2`.`sender_user_id` AS sender_user_id,
`t2`.`created_at` AS created_at
FROM `messages` `t2`
WHERE `t2`.`receiver_user_id` = 50
Any idea why there's a MySQL UNION error. Is it an arel bug?
Secondly, any help with completing the query would be much appreciated.
Update:
Using Arel::Nodes::Union.new works
I think this is more probably a mysql fault, this is a mySQL error text. Something similar is discussed in here, but not exactly this issue.
Try to migrate to another sql server, and check again, or if union all works then use this:
conv = convs1.union(convs2, :all)
Based on documentation.
The problem is actually the parentheses in the sql. It works if I run:
Message.find_by_sql conv.to_sql.delete('()')
which removes the leading "(" and trailing ")"
Weird.. I don't know how I would chain this to complete the query. (Arel::Nodes::Union doesn't have a group method). This is Rails 3.1.4
I had a similar problem and solved it as follows:
def last_messages
Message.find_by_sql("
SELECT messages.*,
(IF(recipient_id = #{id}, 0,1)) as outlast,
users.avatar_name,
users.name
FROM messages
INNER JOIN users
ON users.id=(IF(recipient_id = #{id}, sender_id,recipient_id))
WHERE messages.id IN
( SELECT max(id)
FROM messages
WHERE recipient_id = #{id} OR sender_id = #{id}
GROUP BY (IF(recipient_id = #{id}, sender_id, recipient_id))
)
ORDER BY messages.id DESC")
end
This is the code I used instead in the end
all_msgs = Message.where("messages.sender_user_id = ? OR messages.receiver_user_id = ?",
user.id, user.id)
msg_ids = all_msgs.select("sender_user_id, receiver_user_id, max(id) as max_id")
.group(:sender_user_id, :receiver_user_id).map { |m| m.max_id }
all_msgs = all_msgs.where(:id => msg_ids)