Combine multiple rows into one JSON object/array from single MySQL query - mysql

I am trying to combine two rows of generated json within mysql, my current code outputs two rows (first is user id, second is the time) I want to combine them into one string. I've explored the use of GROUP CONCAT, JSON_MERGE (and JSON_MERGE_PRESERVE) and also JSON_OBJECTAGG. For further info, I am using MYSQL8.
Current output:
unavailability
{"59745190": "1400"}
{"59745190": "1200"}
My MySQL Script:
SELECT JSON_OBJECT(`appointment_with`, TIME_FORMAT(`appointment_datetime`,'%H%i')) as `unavailability`
FROM `appointments`
WHERE `appointment_with` = '59745190'
AND (DATE(`appointment_datetime`) = '2022-03-30' AND `appointment_confirmed` = 1)
Thank you in advance.

Related

How can we split the strings in mysql IN query?

I'm trying to fetch the data in NodeJs using mysql IN query.
I'm getting the data dynamically and need to get data based on textValues;
For example , let textValues = 'a1b, a2b, a3b, a4b' and my query is-
select * from table where values IN (textValues).
but this will not generate the expected output.
As I'll achieve this using
select * from table where values IN ('a1b','a2b','a3b','a4b').
i.e. textValues should be in 'a1b','a2b' which we can't store in any data types like this.
How can we achieve this with MYSQL IN query.
Thank You

Can SqlAlchemy's array_agg function accept more than one column?

I want to return arrays with data from the entire row (so all columns), not just a single column. I can do this with a raw sql statement in Postgresql,
SELECT
array_agg(users.*)
FROM users
WHERE
l_name LIKE 'Br%'
GROUP BY f_name;
but when I try to do it with SqlAlchemy, I'm getting
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'InstrumentedAttribute'
For example, when I execute this query, it works fine
query: Query[User] = session.query(array_agg(self.user.f_name))
But with this I get arrays of rows with only one column value in them (in this example, the first name of a user) whereas I want the entire row (all columns for a user).
I've tried explicitly listing multiple columns, but to no avail. For example I've tried this:
query: Query[User] = session.query(array_agg((self.user.f_name, self.user.l_name))))
But it doesn't work. I get the above error message.
You could use Python feature unpack for create
example = [func.array_agg(column) for column in self.example.__table__.columns]
query = self.dbsession.query(*attach)
And after join results

Inserting DATA in MS Access

I've this code:
SELECT VISA41717.Fraud_Post_Date, VISA41717.Merchant_Name_Raw, VISA41717.Merchant_City, VISA41717.Merchant_Country, VISA41717.Merchant_Category_Code, VISA41717.ARN, VISA41717.POS_Entry_Mode, VISA41717.Fraud_Type, VISA41717.Local_Amt, VISA41717.Fraud_Amt, VISA41717.Purch_Date, VISA41717.Currency_Code, VISA41717.Cashback_Indicator, VISA41717.Card_Account_Num
FROM VISA41717 LEFT JOIN MASTERCARD_VISA ON VISA41717.ARN=MASTERCARD_VISA.MICROFILM_NUMBER
WHERE VISA41717.ARN IS NULL OR MASTERCARD_VISA.MICROFILM_NUMBER IS NULL
ORDER BY VISA41717.ARN;
this is really works, But I need to match the first 6 digit of VISA41717.Card_Account_Num from BIN.INT to get the other data from BIN table and combined it all in one table only.
it should be this way:
Can you help me with this.
thanks!
What do you mean by 'all in one table'? Just build a query that joins tables.
Try:
SELECT ... FROM VISA41717 RIGHT JOIN BIN ON Left(VISA41717.Card_Account_Num, 6) = Bin.Int ...
Won't be able to build this join in Design View, use SQL View. Or build a query object that creates a field by extraction of the 6 characters and then build another query that includes that query and MASTERCARD_VISA and BIN tables.

Cron Bash - select data from two MySQL tables & export to CSV

I am really bad at creating MySQL queries and need some help. I need to create a bash file to be triggered by a cron job once a week - that queries two tables, grabbing data where the user IDs match in both tables, and adding the select data to a CSV export file. I would like the CSV to be comma separated. Right now the best I can get it tab separated.
My issue in getting this query to run is my syntax (which I know is wrong as I have simply stolen snippets from various articles online). I did get each DB query to work separately (grabbing from one table with one query and another table with another query). Now I need to combine them to grab only the data I need.
Here's my current (non working) query:
#!/bin/bash
mysql -u USERNAME --password=PASSWORD --database=xxxx_DBNAME --execute='SELECT `xxxx_videotraining_user.user_id`, `xxxx_videotraining_user.training_title`, `xxxx_videotraining_user.status`, `xxxx_users.id`, `xxxx_users.name`, `xxxx_users.user_employer`, `xxxx_users.user_ss_number` WHERE `xxxx_videotraining_user.user_id` = `xxxx_users.id` AND `xxxx_videotraining_user.status` = "Completed" AND `xxxx_users.user_ss_number` > "1" ORDER BY `xxxx_videotraining_user.user_id` LIMIT 0, 10000 AND ' -C > /home/xxxx/subs/vtc/DB_EXPORTS/xxxx_videotraining_completed.csv
I think you can see what I am trying to accomplish here - any help would be greatly appreciated!
It also looks like you're missing your FROM clause, have an trailing AND clause (as noted in other answers), and are quoting things incorrectly. This looks to be your original query:
SELECT `xxxx_videotraining_user.user_id`,
`xxxx_videotraining_user.training_title`,
`xxxx_videotraining_user.status`,
`xxxx_users.id`,
`xxxx_users.name`,
`xxxx_users.user_employer`,
`xxxx_users.user_ss_number`
WHERE `xxxx_videotraining_user.user_id` = `xxxx_users.id` AND
`xxxx_videotraining_user.status` = "Completed" AND
`xxxx_users.user_ss_number` > "1"
ORDER BY `xxxx_videotraining_user.user_id`
LIMIT 0, 10000 AND
I think you want to add the FROM clause, quote the table and field separately, and remove the trailing AND, to get something like:
SELECT `xxxx_videotraining_user`.`user_id`,
`xxxx_videotraining_user`.`training_title`,
`xxxx_videotraining_user`.`status`,
`xxxx_users`.`id`,
`xxxx_users`.`name`,
`xxxx_users`.`user_employer`,
`xxxx_users`.`user_ss_number`
FROM `xxxx_users`,
`xxxx_videotraining_user`
WHERE `xxxx_videotraining_user`.`user_id` = `xxxx_users`.`id` AND
`xxxx_videotraining_user`.`status` = "Completed" AND
`xxxx_users`.`user_ss_number` > "1"
ORDER BY `xxxx_videotraining_user`.`user_id`
LIMIT 0, 10000
There are other things that could be done to shorten the size of the query and make it a bit cleaner, but that should get it functional.
One thing I know that helps me when dealing with long queries is to format them like this, with the main clauses separated out so you can see the different sections of the query.
Let me know if that helps.
I think AND shouldn't be here:
LIMIT 0, 10000 AND

nested "select " query in mysql

hi i am executing nested "select" query in mysql .
the query is
SELECT `btitle` FROM `backlog` WHERE `bid` in (SELECT `abacklog_id` FROM `asprint` WHERE `aid`=184 )
I am not getting expected answer by the above query. If I execute:
SELECT abacklog_id FROM asprint WHERE aid=184
separately
I will get abacklog_id as 42,43,44,45;
So if again I execute:
SELECT `btitle` FROM `backlog` WHERE `bid` in(42,43,44,45)
I will get btitle as scrum1 scrum2 scrum3 msoffice
But if I combine those queries I will get only scrum1 remaining 3 atitle will not get.
You Can Try As Like Following...
SELECT `age_backlog`.`ab_title` FROM `age_backlog` LEFT JOIN `age_sprint` ON `age_backlog`.`ab_id` = `age_sprint`.`as_backlog_id` WHERE `age_sprint`.`as_id` = 184
By using this query you will get result with loop . You will be able to get all result with same by place with comma separated by using IMPLODE function ..
May it will be helpful for you... If you get any error , Please inform me...
What you did is to store comma separated values in age_sprint.as_backlog_id, right?
Your query actually becomes
SELECT `ab_title` FROM `age_backlog` WHERE `ab_id` IN ('42,43,44,45')
Note the ' in the IN() function. You don't get separate numbers, you get one string.
Now, when you do
SELECT CAST('42,43,44,45' AS SIGNED)
which basically is the implicit cast MySQL does, the result is 42. That's why you just get scrum1 as result.
You can search for dozens of answers to this problem here on SO.
You should never ever store comma separated values in a database. It violates the first normal form. In most cases databases are in third normal form or BCNF or even higher. Lower normal forms are just used in some special cases to get the most performance, usually for reporting issues. Not for actually working with data. You want 1 row for every as_backlog_id.
Again, your primary goal should be to get a better database design, not to write some crazy functions to get each comma separated number out of the field.