using mysql stored-function with select query - php

let me explain my purpose first, i have an vehicle booking application where, visitor will add start date and end date of his journey, in the database there is list of drivers with there availability (available_from_date and available_to_date) which is kind of duration during which they are operating, there is an field for exclude_dates for some specific dates when they are not working.
the application needs to find a list of vehicles which are available during the journey dates entered by the user.
for example user enters he want to go from place A to B during 13th sept, 2014 to 17th sept, 2014
then database needs to return a list of taxi which are available during this period and must not have any exclude date within this period.
Now i have stored the exclude_dates in comma separated format in table (i could have created a separate table but then it would take much more time for a query to execute)
I was trying to create a mysql function which would be called within the actual search query and would return true if there is some there is some excluded date present within the duration and false if not.
these are the queries that i have written
SELECT id, exclude_dates
FROM `taxi_route`
WHERE status = 1
AND `to_city` = 'Surat'
AND `from_city` = 'Ahmedabad'
AND `trip_type` = 2
AND `available_from_date` <= '2014-09-13'
AND available_to_date >= '2014-09-17'
AND STR_TO_DATE((SELECT `split`(exclude_dates, ',', 1)),'%d-%m-%Y')
NOT BETWEEN STR_TO_DATE('13-09-2014','%d-%m-%Y')
AND STR_TO_DATE('17-09-2014','%d-%m-%Y')
Split is a function i have created in mysql to separate the dates present in comma format
DELIMITER $$
CREATE FUNCTION split( str VARCHAR(500), delchar VARCHAR(2), x INT )
RETURNS VARCHAR(500)
BEGIN
RETURN SUBSTR(SUBSTRING_INDEX(str, delchar, x),
LENGTH(SUBSTRING_INDEX(str, delchar, x-1))+IF(x > 1, 2, 1));
END$$
DELIMITER ;
this works fine as far as i pass 1 in split(exclude_dates, ',', 1) , but if the exclude_dates have more then one date then this will not work
can someone please suggest or guide, how this can be accomplished.
snapshot of database is here http://i.imgur.com/JaI8MSx.png

Your query is most likely going to take more time to execute than defining a separate table for exclusion dates. It's not a good practice using comma separated list inside a column for searching purposes, this is against normalization rules.
You should define your tables separately, (e.g. taxi, taxi_route, taxi_route_exclusion, route_exclusion) and later add necessary indexes to make your searches more efficient.
Example:
taxi
---------
id
country
***
***
***
taxi_route
-------------------
id
taxi_id
available_from_date
available_to_date
from_city
to_city
route_exclusion
---------------
id
taxi_id
exclusion_date
And also add a relation table between taxi_route and route_exclusion tables to represent many-to-many relationship. Later define foreign keys on taxi_route_route_exclusion table to point taxi_route and route_exclusion tables.
taxi_route_route_exclusion
--------------------------
taxi_route_id
route_eclusion_id
Define foreign keys like:
taxi_route.taxi_id -> taxi.id
taxi_route_route_exclusion.taxi_route_id -> taxi_route.id
taxi_route_route_exclusion.route_exclusion_id -> route_exclusion.id
Define indexes like:
taxi: IX1 (status, trip_type)
taxi_route: IX1(to_city, from_city, available_from_date, available_to_date)
Your final query should look like this:
SELECT tr.id, re.exclusion_date
FROM `taxi_route` tr JOIN `taxi_route_route_exclusion` trre
ON tr.id = trre.taxi_route_id
JOIN `route_exclusion` re
ON re.id = trre.route_exclusion_id
JOIN `taxi` t
ON t.id = tr.id
WHERE
t.status = 1
AND t.trip_type = 2
AND tr.to_city = 'Surat'
AND tr.from_city = 'Ahmedabad'
AND tr.available_from_date <= '2014-09-13'
AND tr.available_to_date >= '2014-09-17'

Related

Query Reports from comma separated JSON mysql field

this is my first question. Apologies if I don't conform with the required rules. I have tried my best and
Problem--
I have a problem with a project am working on. It is medical based. I have these three tables that I need to get reports from
DB structure--
diseaseTable which has columns
diseaseID | diseaseName
diseaseID stores an integer i.e 1, 3, 4,..
dieseaseName stores name of disease e.g Hypertension, Malaria, ..e.tc
I also have patientsTable which has these key columns
patientID - which is an autoincrement int
patientName - name of patient
created_at - date and time of registration of the patient
Lastly there is treatment table which contains
treatmentID -autoincrement int
patient - contains the id of the patient which is a foreing key of patientsTable
created_at and updated_at for timestamps
diseaseTreated (which is my column of interest) Stores values in json comma separated fields.
I have already checked all results from https://stackoverflow.com/search?q=mysql+comma+separated+fields but none seems to solve my problem. I have checked on ways to restructure mysql schema but i would have too many tables to store the diseases diagnised from each patient. In addition one patient might be diagnosed with multiple diseases and a disease can be added any time. I might have almost 100 of them. If ID of Hypertension is 1 and arthritis is 2 a patient with both will have the
diseaseTreated field with "1","2" in the treatment table
Solution Expected--
I need to get reports for first time a specific disease has been treated for the first time or second time and more i.e revisit for treatment of the same disease (if i wanted to know how many cases of hypertension are for the first time, and how many cases of hypertension are recurrent)
Example - New cases report
Disease | New Cases
Hypertension | 4
Example - Recurrent cases report
Disease | New Cases
Hypertension | 1
Arthritis | 2
Am using Laravel I have attempted a lot of solutions but this is what i find too close to get what I need: Others I have attempted was looping through different array results i have queried from the database by using joins but I havent posted them because they have yielded nothing important.
$diseaseID
$countedDiseaseCases = DB::select('select * from treatmentTable where JSON_CONTAINS(diseases, \'[\"'.$diseaseID.'\"]\')')
This one would get me the rows with a specific disease and by using php count() on the result I get an int as 3 which is OK but I haven't got to put it as I expect filter and differentiate new and recurrent cases.
Thanks,
Any suggestion will be highly appreciated
If the deseaseTreated column is json, couldn't you add an isNew key and when the patient comes in for a second visit, flip that key to false or something similar?
Now when you want to make the report you can get counts on all of them.
//example deseaseTreated value
{
"deseases": [
{
"deseaseID":"Value",
"isNew":Boolean,
...
},
{...}
]
}
$records = DB::select('select * from treatment');
$diseases = DB::select('select * from diseases');
foreach ($diseases as $disease) {
$disease['count_new'] = 0;
}
foreach ($records as $record) {
$json = json_decode($record['diseaseTreated']);
foreach ($json['diseases'] as disease_index) {
if ($disease_index['isNew']) {
foreach ($diseases as &$d) {
if ($d['diseaseID'] == $disease_index['diseaseID']) {
$d['count_new']++;
}
}
}
}

concatenate query result in a string

I am getting a db result as 3 rows (Please see image link below).
The sql statement used is
select tevmkt.ev_mkt_id, tevmkt.name, tevmkt.ev_id, tevoc.ev_oc_id,
tevoc.desc, tevoc.fb_result, tevoc.lp_num, tevoc.lp_den,
tev.start_time
from tevmkt, tev,tevoc
where tevmkt.name = '|Match Result|' and tev.ev_id=tevmkt.ev_id and
tevoc.ev_mkt_id=tevmkt.ev_mkt_id and tev.start_time>=Today;
I will like to use php to concatenate each of the 3 rows into string or maybe use SQL statement.
So, the first 3 rows will display as ;
632274|Match Result||Draw||Aldershot Town||Arsenal FC|
And the next 3 rows
637799|Match Result||Draw||Southend United||Oxford United|
You can use concat
Sample base on your query
select CONCAT(tevmkt.ev_mkt_id, tevmkt.name, tevmkt.ev_id, tevoc.ev_oc_id,
tevoc.desc, tevoc.fb_result, tevoc.lp_num, tevoc.lp_den,
tev.start_time)
from tevmkt, tev,tevoc
where tevmkt.name = '|Match Result|' and tev.ev_id=tevmkt.ev_id and
tevoc.ev_mkt_id=tevmkt.ev_mkt_id and tev.start_time>=Today;
For what I see your model looks something like this:
CREATE TABLE tevmkt(
ev_mkt_id INT,
ev_id INT,
name CHAR(25)
);
CREATE TABLE tev(
ev_id INT,
start_time DATETIME YEAR TO SECOND
);
CREATE TABLE tevoc(
ev_mkt_id INT,
desc CHAR(25),
fb_result CHAR(1),
lp_num SMALLINT,
lp_den SMALLINT
);
You join tevmkt with tev by ev_id in a 1-to-1 relation.
You filter the records on tevmkt using the name field and the records on tev using the start_time field.
Now, you join the tevmkt with the tevoc by ev_mkt_id in a one to many relation, for what I see 1-to-3.
Your goal is to have a 1-to-1 also. Looking at you example I see three rows for each event and I conclude that they are:
1 row for home team, where fb_result is H;
1 row for away team, where fb_result is A;
1 row for result, I'm not sure on this one so I will handle it with care;
If this is the case, you can get your result set straigth using the next joins and filters:
SELECT
tevmkt.ev_mkt_id,
tevmkt.name,
(
TRIM(tevoc_result.desc) ||
TRIM(tevoc_away.desc) ||
TRIM(tevoc_home.desc)
) AS desc
FROM tevmkt
JOIN tev ON
tev.ev_id = tevmkt.ev_id
JOIN tevoc tevoc_result ON
tevoc_result.ev_mkt_id = tevmkt.ev_mkt_id
JOIN tevoc tevoc_away ON
tevoc_away.ev_mkt_id = tevmkt.ev_mkt_id
JOIN tevoc tevoc_home ON
tevoc_home.ev_mkt_id = tevmkt.ev_mkt_id
WHERE
tevmkt.name = '|Match Result|'
AND tev.start_time >= TODAY
AND tevoc_result.fb_result NOT IN ('H', 'A')
AND tevoc_away.fb_result = 'A'
AND tevoc_home.fb_result = 'H'
;

PHP/MySQL make top 10 out of selection

A user can input it's preferences to find other users.
Now based on that input, I'd like to get the top 10 best matches to the preferences.
What I thought is:
1) Create a select statement that resolves users preferences
if ($stmt = $mysqli->prepare("SELECT sex FROM ledenvoorkeuren WHERE userid = you"))
$stmt->bind_result($ownsex);
2) Create a select statement that checks all users except for yourself
if ($stmt = $mysqli->prepare("SELECT sex FROM ledenvoorkeuren WHERE userid <> you"))
$stmt->bind_result($othersex);
3) Match select statement 1 with select statement 2
while ($stmt->fetch()) {
$match = 0;
if ($ownsex == $othersex) {
$match = $match + 10;
}
// check next preference
4) Start with a variable with value 0, if preference matches -> variable + 10%
Problem is, I can do this for all members, but how can I then select the top 10???
I think I need to do this in the SQL statement, but I have no idea how...
Ofcourse this is one just one preference and a super simple version of my code, but you'll get the idea. There are like 15 preference settings.
// EDIT //
I would also like to see how much the match rating is on screen!
Well, it was a good question from the start so I upvoted it and then wasted about 1 hour to produce the following :)
Data
I have used a DB named test and table named t for our experiment here.
Below you can find a screenshot showing this table's structure (3 int columns, 1 char(1) column) and complete data
As you can see, everything is rather simple - we have a 4 columns, with id serving as primary key, and a few records (rows).
What we want to achieve
We want to be able to select a limited set of rows from this table based upon some complex criteria, involving comparison of several column's values against needed parameters.
Solution
I've decided to create a function for this. SQL statement follows:
use test;
drop function if exists calcMatch;
delimiter //
create function calcMatch (recordId int, neededQty int, neededSex char(1)) returns int
begin
declare selectedQty int;
declare selectedSex char(1);
declare matchValue int;
set matchValue = 0;
select qty, sex into selectedQty, selectedSex from t where id = recordId;
if selectedQty = neededQty then
set matchValue = matchValue + 10;
end if;
if selectedSex = neededSex then
set matchValue = matchValue + 10;
end if;
return matchValue;
end//
delimiter ;
Minor explanation
Function calculates how well one particular record matches the specified set of parameters, returning an int value as a result. The bigger the value - the better the match.
Function accepts 3 parameters:
recordId - id of the record for which we need to calculate the result(match value)
neededQty - needed quantity. if the record's qty matches it, the result will be increased
neededSex - needed sex value, if the record's sex matches it, the result will be increased
Function selects via id specified record from the table, initializes the resulting match value with 0, then makes a comparison of each required columns against needed value. In case of successful comparison the return value is increased by 10.
Live test
So, hopefully this solves your problem. Feel free to use this for your own project, add needed parameters to function and compare them against needed columns in your table.
Cheers!
Use the limit and offset in query:
SELECT sex FROM ledenvoorkeuren WHERE userid = you limit 10 offset 0
This will give the 10 users data of top most.
You can set a limit in your query like this:
SELECT sex FROM ledenvoorkeuren WHERE userid <> yourid AND sex <> yourpreferredsex limit 0, 10
Where the '0' is the offset, and the '10' your limit
More info here
you may try this
SELECT sex FROM ledenvoorkeuren WHERE userid = you limit 0, 10 order by YOUR_PREFERENCE

Computing an average from different tables

I am sorry for a verlo long question, just trying to explain in details. My formatting is not very good, sorry for that as well. I had a PHP/ MySQL App that essentially was not truly relational as I had one large table for all student scores. Among other things, I was able to calculate the average score for each subject, such that the average appeared alongside a student's score. Now I have since split the table up, to have a number of tables which I am successfully querying and creating School Report Cards as before. The hardship is that I can no longer calculate the avaerages for any subject.
Since I had one table with 5 subjects and each of the subjects had 2 tests, I queried for data and calculated the average as follows:
The one table (Columns):
id date name exam_no term term year eng_mid eng_end mat_mid mat_end phy_mid phy_end bio_mid bio_end che_mid che_end
The one query:
$query = "SELECT * FROM pupils_records2
WHERE grade='$grade' && class='$class' && year = '$year' && term ='$term'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) > 0) {
$num_rows=mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
//English
$eng_pupils1{$row['fname']} = $row['eng_mid'];
$eng_pupils2{$row['fname']} = $row['eng_end'];
$mid=(array_values($eng_pupils1));
$end=(array_values($eng_pupils2));
$add = function($a, $b) { return $a + $b;};
$eng_total = array_map($add, $mid, $end);
foreach ($eng_total as $key => $value){
if ($value==''){
unset ($eng_total[$key]);
}
}
$eng_no=count($eng_total);
$eng_ave=array_sum($eng_total)/$eng_no;
$eng_ave=round($eng_ave,1);
//Mathematics
$mat_pupils1{$row['fname']} = $row['mat_mid'];
$mat_pupils2{$row['fname']} = $row['mat_end'];
$mid=(array_values($mat_pupils1));
$end=(array_values($mat_pupils2));
$add = function($a, $b) { return $a + $b;};
$mat_total = array_map($add, $mid, $end);
foreach ($mat_total as $key => $value){
if ($value==''){
unset ($mat_total[$key]);
}
}
print_r($mat_total);
$mat_no=count($mat_total);
echo '<br />';
print_r($mat_no);
$mat_ave=array_sum($mat_total)/$mat_no;
$mat_ave=round($mat_ave,1);
}
}
//Biology
etc
I split the table into separate tables and have names in a separate table, not needed for calculating avaerages, so I will not show it here. Each subject table tajkes the following form:
id date exam_no term year grade class test*
*Test would be eng_mid or eng_end or mat_mid etc.
Because I had only one query which returned 10 rows (5 subjects each with two tests: e.g. eng_mid (English Mit exam), eng_end (english end of term test), I was able to capture all rows in one call and pack each subject into an array, and then work out the class average, with the help of array_map. It may not be elegant, but it worked very well. Now, I have each test in it's own table.
I was trying to write a joint so as to get a signle resultset but the query fails. The columns as like:
I know that the database design is not anything to be proud off, but coming from a huge single table, this is a massive step (worthy a pat on the shoulder).
What I wish to do is to be able to query all my data and calculate class averages (about 30 students in each class). I tried to use separate queries but I ran into a wall, in that previously I would use the WHILE conditional as shown after the query for it to pull all rows and create an array from which I could get desired results. Now several queries just makes me confused as to how I can archieve the same results since a join is not working. Also I am having a separate $row variable, and that throws me further off balance!
Is it even possible to do averages as I did on my infamous one table (from the dark side) or is my table design so messed up, what I want just isn't humanly possible?
Please any help will be deeply appreciated.
Try using union. It would be something like
select grade, test from math
union all
select grade, test from english
union all
....
Also, in my opinion, better design would be to have table exams something like that (warning, pseudo-DML):
id int primary key,
student_id int foreign key students
subject_id int foreign key subjects
exam_type_id int foreign key exam_types
grade int(????)
exam_types table would be just midterm and final, but you'll be able to easily support more types in future, if required.
subjects table will store all kinds of subjects you have (at this time there will be only five of them: math, eng, phy, etc.
The averaging query would be as simple as (yes, you can actually do aggregation in the query itself)
select student_id, avg(grade)
from exams
group by student_id

query to count MySQL rows

Trying to get a count (to later multiply with a rate) of names in upto (if data is present in one or more) four rows. In other words, there is a price per person occupying a room. So, I want to count the number of persons in the room by names entered on the form and saved in the database table.
I could simply add a field where the user also selects the number of people in addition to completeing the name fields but this seems redundant (and prone to error).
Setup
Table: 1.clients which has columns:
id,
tourbk_id,
tourstart,
roomtype1,
client1_name,
client2_name,
client3_name,
client4_name
Question
I have a query which currently checks the roomtype to the per person price for that room type and is working to produce the result but, of course, it is only returning (for two people in a room) the price person for double occupancy.
E.g.: (per person prices)... single = $10; double = $20; triple = $30; quad = $40
My current result for double room is $20 (which echo's next to "Price per person". I need a query to count the total persons in this double and multiple times the rate ... "Total: query[$20 * 2]"
How do I code a query to count the "client_name" entries in a table?
Here I've added a virtual column named ClientCount which is the count of clients in the room. I like to use client1_name > '' because it works whether you use blanks or NULLs, and saves me from asking a question.
SELECT
id,
tourbk_id,
tourstart,
roomtype1,
client1_name,
client2_name,
client3_name,
client4_name,
CASE WHEN client1_name > '' THEN 1 ELSE 0 end +
CASE WHEN client2_name > '' THEN 1 ELSE 0 end +
CASE WHEN client3_name > '' THEN 1 ELSE 0 end +
CASE WHEN client4_name > '' THEN 1 ELSE 0 end ClientCount
FROM TBL
You ought to consider normalising your schema by having a separate client_names table that relates a single name column to a single booking identifier: multiple clients would then be represented by multiple records in that new table. You would count clients with:
SELECT COUNT(*) FROM client_names WHERE booking_id = ...
However, with your current structure (and assuming that the name columns are NULL if there is no such client), you could do:
SELECT (client1_name IS NOT NULL)
+ (client2_name IS NOT NULL)
+ (client3_name IS NOT NULL)
+ (client4_name IS NOT NULL)
AS client_count
FROM clients
-- etc.
and, as a round-about way of doing it I thought of the following which also works (will just need to make a case for the 1, 2, 3, and 4 ["if roomtype1='sgl', then $mult=1, if roomtype='dbl', then $mult=2...] multiplyer to check for the other room types):
$total = ($roomrate['roomprice'] * 2);
echo "Total this booking : ";
echo $total;
thanks to all for the help!

Categories