Sample Header Ad - 728x90

How to calculate quantity based on a boolean field and retrieve values from a JSON field in MySQL

0 votes
1 answer
81 views
I'm working with a table called price_options that has the following fields: id, slots, list_slots, and quantity. Issue Description ========== -------- My objective is to calculate the quantity for each price option based on the boolean value of the slots field. If slots is set to true, I need to retrieve the quantity from the list_slots field, which contains JSON data structured like this: [{"start":"09:00","quantity":30},{"start":"09:30","quantity":30}]. Otherwise, I should use the quantity field directly. ---------- 1- SQL For Creating Table: ------------------- CREATE TABLE price_options ( id INT UNSIGNED PRIMARY KEY, slots BOOLEAN, quantity INT, list_slots TEXT NULL ); 2- Adding data in table for case: 1 ----------- INSERT INTO price_options (slots, quantity, list_slots) VALUES (TRUE, 0, '[{"start":"09:00","quantity":30},{"start":"09:30","quantity":30}]'); 3 -Adding data in table for case: 2 ----------- INSERT INTO price_options (slots, quantity, list_slots) VALUES (FALSE, 30, NULL); ---------- 4- Required Output for Both Cases: =============================== **Case 1:** ----------- **slots** field is **true**, i want total quantity calculated from **list_slots** field. Output should be (30+30) = 60 **Case 2:** ----------- **slots** field is **false**, i want total quantity from quantity field. This time we will ignore **list_slots** field. Output should be: 30 ---------- Note: ----- 1. **list_slots** field type is text. 2. The MySQL version I'm using is **10.4.24-MariaDB** (Xampp). ---------- I hope it helps to understand the issue Any help or guidance on how to approach this would be greatly appreciated. Thank you.
Asked by Khuzema (13 rep)
Jun 14, 2023, 12:49 PM
Last activity: Jun 14, 2023, 07:47 PM