So I have query the output is supposed to show all medically trained staff and all volunteers that have first aid:
SELECT Concat (s.staff_fname, ' ', s.staff_lname) AS Staff_Name,
s.medically_trained,
s.staff_email_address,
Concat(v.volunteer_fname, ' ', v.volunteer_lname) AS Volunteer_Name,
v.first_aid,
v.volunteer_email_address
FROM volunteer v
JOIN staff s
ON v.volunteerid = s.staffid
WHERE s.medically_trained = ' yes'
AND v.first_aid = ' yes'
however when I execute my code it says empty set. What am I doing wrong?
I am a beginner coder so please dont judge if ive made an obvious mistake lol
THANK YOU!
First remove the space from 'yes' , it may also cause this issue.You may get the not null value in result.
If it is still blank then try to run the where clause individually on both of the tables,
Select *
FROM volunteer v where v.first_aid = 'yes';
and
select * from staff s
WHERE s.medically_trained = 'yes' ;
and check whether any one of it is giving you null as a result, if yes then your answer is correct.
Remove the spaces in where section:
SELECT Concat (s.staff_fname, ' ', s.staff_lname) AS Staff_Name,
s.medically_trained,
s.staff_email_address,
Concat(v.volunteer_fname, ' ', v.volunteer_lname) AS Volunteer_Name,
v.first_aid,
v.volunteer_email_address
FROM volunteer v
JOIN staff s
ON v.volunteerid = s.staffid
WHERE s.medically_trained = 'yes' /* <-- */
AND v.first_aid = 'yes' /* <-- */
Try this:
SELECT CONCAT(s.staff_fname,' ', s.staff_lname)AS Name,s.medically_trained AS Trained,s.staff_email_address AS Email_Address,'STAFF' cType
FROM staff s
WHERE s.medically_trained = ' yes'
UNION ALL
SELECT Concat(v.volunteer_fname, ' ', v.volunteer_lname) AS Name,v.first_aid AS Trained,v.volunteer_email_address AS Email_Address,'VOLUNTEER' cType
FROM volunteer v
WHERE v.first_aid = ' yes'
I used UNION ALL for the two table because I dont think Volunteer_ID will be Equivalent to STAFF_ID. I included cType Column for you to identify if the record was from Staff table or Volunteer
If you do a CONCAT('foo', 'null'), the result will be null. Check to see if that's not the case.
Also, it could be from either the JOIN clause or WHERE clause. Try running the query without JOIN and then without the WHERE clause and see if you'll still have empty sets.
Related
We have a scenario where users answer some questions related to a parent entity that we'll call a widget. Each question has both a numeric and word answer. Multiple users answer each question for a given widget.
We then display a row for each widget with the average numeric answer for each question. We do that using a MySQL pseudo-pivot with dynamic columns as detailed here So we end up with something like:
SELECT widget_id, ...
ROUND(IFNULL(AVG(CASE
WHEN LOWER(REPLACE(RQ.question, ' ', '_')) = 'overall_size' THEN
if(RA.num = '', 0, RA.num) END),0) + .0001, 2) AS `raw_avg_overall_size`,
...
... where overall_size would be one of the question types related to the widget and might have "answers" from 5 users like 1,2,2,3,1 to that question for a given widget_id based on the answer options below:
Answers
answer_id
answer_type
num
word
111
overall_size
1
x-large
112
overall_size
2
large
113
overall_size
3
medium
114
overall_size
4
small
115
overall_size
5
x-small
So we would end up with a row that had something like this:
widget_id
average_overall_size
115
1.80
What we can't figure out is then given if we round 1.80 to zero precision we get 2 in this example which is the word value 'large' from our data above. We like to include that in the query output too so that end up with:
widget_id
raw_average_overall_size
average_overall_size
115
1.80
large
The issue is that we do not know the average for the row until the query runs. So how can we then reference the word value for that average answer in the same row when executing the query?
As mentioned we are pivoting into a variable and then run another query for the full execution. So if we join in the pivot section, that subquery looks something like this:
SET #phase_id = 1;
SET SESSION group_concat_max_len = 100000;
SET #SQL = NULL;
SET #NSQL = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT(
'ROUND(IFNULL(AVG(CASE
WHEN LOWER(REPLACE(RQ.short_question, '' '', ''_'')) = ''',
nsq,
''' THEN
if(RA.answer = '''', 0, RA.answer) END),0) + .0001, 2) AS `',
CONCAT('avg_raw_',nsq), '`,
REF.value, -- <- ******* THIS FAILS **** --
ROUND(IFNULL(STDDEV(CASE
WHEN LOWER(REPLACE(RQ.short_question, '' '', ''_'')) = ''',
nsq,
''' THEN RA.answer END), 0) + .0001, 3) AS `',
CONCAT('std_dev_', nsq), '`
'
)
ORDER BY display_order
) INTO #NSQL
FROM (
SELECT FD.ref_value, FD.element_name, RQ.display_order, LOWER(REPLACE(RQ.short_question, ' ', '_')) as nsq
FROM review_questions RQ
LEFT JOIN form_data FD ON FD.id = RQ.form_data_id
LEFT JOIN ref_values RV on FD.ref_value = RV.type
WHERE RQ.phase_id = #phase_id
AND FD.element_type = 'select'
AND RQ.is_active > 0
GROUP BY FD.element_name
HAVING MAX(RV.key_name) REGEXP '^[0-9]+$'
) nq
/****** suggested in 1st answer ******/
LEFT JOIN ref_values REF ON REF.`type` = nq.ref_value
AND REF.key_name = ROUND(CONCAT('avg_raw_',nsq), 0);
So we need the word answer (from the REF join's REF.value field in the above code) in the pivot output, but it fails with 'Unknown column REF.value. If we put REF.value in it's parent query field list, that also fails with the same error.
You'll need to join the table/view/query again to get the 'large' value.
For example:
select a.*, b.word
from (
-- your query here
) a
join my_table b on b.answer_id = a.answer_id
and b.num = round(a.num);
An index on my_table (answer_id, num) will speed up the extra search.
This fails, leading to the default of "2":
LOWER(REPLACE(RQ.question, ' ', '_')) = 'overall_size'
That is because the question seems to be "average_overall_size", not "overall_size".
String parsing and manipulation is the pits in SQL; suggest using the application to handle such.
Also, be aware that you may need a separate subquery to compute aggregate (eg AVG()), else it might not be computed over the set of values you think.
Query into temp table, then join
First query should produce table as follows:
CREATE temp table, temp_average_size
widget_id
average_overall_size
rounded_average_size
115
1.80
2
LEFT JOIN
select s.*, a.word
from temp_average_size s LEFT JOIN answers a
ON (s.rounded_average_size = a.num AND a.answer_type = 'overall_size)
I want to update a table with a query from another table.
I want to get mixed informations from a combination of two tables.
And then update one of the two tables with them.
Here is what I did :
UPDATE commande as C,
(
SELECT CONCAT (input_hauteur_sous_collecteur, ' x ', input_largeur_hors_tout, ' x ', input_epaisseur, ' - ', input_pas_ailettes)
AS 'ligne_sage'
FROM commande as C, faisceaux_ta as F
WHERE C.commande_type_faisceaux = 'TA'
AND C.commande_id_faisceaux = F.id
) AS src
SET
C.ligne_sage = src.ligne_sage
WHERE
C.commande_type_faisceaux = "TA"
/* And I got MySQL running the command and never ending without error notification... */
EDIT : Actually it finally works in more than 5 minutes, the problem is that I have the same values (first line of the SELECT result table) in each lines...
What shall I do to make it work ?
(the SELECT CONCAT subquery is properly working)
You got this because you didn't filter results between tables. You need to add and filter in the where clause. Something like (see last line). I don't have your tables defs :-(
UPDATE commande as C,
(
SELECT CONCAT (input_hauteur_sous_collecteur, ' x ', input_largeur_hors_tout, ' x ', input_epaisseur, ' - ', input_pas_ailettes)
AS 'ligne_sage'
FROM commande as C, faisceaux_ta as F
WHERE C.commande_type_faisceaux = 'TA'
AND C.commande_id_faisceaux = F.id
) AS src
SET
C.ligne_sage = src.ligne_sage
WHERE
C.commande_type_faisceaux = "TA"
AND c.commandId = src.commandId
i dont have much expiriance with SQL and i am trying to crack my head on this query.
i have 3 tables: Projects, Calculator and partialBilling
(note: the 'calculator' columns you see at the code ive added 'k','l','m' etc are real...i didnt gave them those names...).
the query is working fine but part of the values that i am expecting from the aggregate function ('sumofTotal' column) are returning as null values and and they should not be null.
I would be grateful if someone point out the mistake in the query.
SELECT Projects.SpCall,Projects.CustName,Projects.CustNumber
,Projects.ReceiveDate,Projects.StartDate,Projects.ProjectType
,Calculator.AN,Projects.Professional,Projects.PmUserName
,Projects.AcountManager,Projects.CrmCallNum,Projects.ProjectCategory
,Projects.CallNum,Projects.ContactName,Projects.ContactPhone
,Projects.ContactEmail,Projects.HiddenNote,Projects.RowColor
, Projects.HeaderCellText,
SUM(Calculator.K + Calculator.L + Calculator.M + Calculator.N + Calculator.AD + Calculator.AR) AS sumofTotal
,partialBilling.Ammount FROM Projects LEFT JOIN Calculator ON Projects.SpCall=Calculator.AQ
LEFT JOIN partialBilling ON Projects.SpCall = partialBilling.spCall
WHERE PmUserName= 'JOHN DOE'AND OpertionalStatus
<> 'Billed' AND OpertionalStatus<> 'Finished' AND
OpertionalStatus<> 'Passed To Billing' AND OpertionalStatus<> 'Scanning'
AND OpertionalStatus<> 'Ended'
AND OpertionalStatus<> 'Green Billing'
AND (GeneralStatus= 'Passed To Project Manager'
OR GeneralStatus= 'Astrategic Project')
GROUP BY Projects.SpCall,Projects.CustName,Projects.CustNumber
,Projects.ReceiveDate,Projects.StartDate,Projects.ProjectType
,Calculator.AN,Projects.Professional,Projects.PmUserName
,Projects.AcountManager,Projects.CrmCallNum,Projects.ProjectCategory
,Projects.CallNum,Projects.ContactName,Projects.ContactPhone
,Projects.ContactEmail,Projects.HiddenNote,Projects.RowColor
, Projects.HeaderCellText,partialBilling.Ammount;
Instead of proprietary IFNULL better use Standard SQL COALESCE:
SUM(COALESCE(Calculator.K,0) + COALESCE(Calculator.L,0), ...`
Or maybe a bit more efficient:
SUM(COALESCE(Calculator.K,0)) + SUM(COALESCE(Calculator.L,0)), ...`
Try to use IFNULL()
SUM(IFNULL(Calculator.K,0) + ... + IFNULL(Calculator.AR,0)) AS sumofTotal
You can use an expression like ifnull('column_name' , '') in place of column_name.
Hi I have a query which is working but I would like to remove certain values from the results.
At the moment I have WHERE (pafaddresses.CountryName !="England") but I would like this to be Where is not England and where is not Wales, I cannot get it to work for two != statements, I have tried Where !="England" or "Wales", without any success.
Any help would be appreciated
SELECT
visits.VisitPk,
visits.ClientFk,
visits.ClientSiteFk,
visits.AssessorFk,
visits.VisitStartDate,
visits.VisitEndDate,
visits.Duration,
visits.VisitStatus,
visits.TargetDate,
CONCAT(MONTHNAME(TargetDate), ' ', YEAR(TargetDate)) AS TargetMonth,
pafaddresses.PostCode,
visits.`Long`,
visits.Lat,
pafaddresses.id,
pafaddresses.CountryName,
CONCAT(Clients.ClientName, ', ', clientsites.SiteName, ', ', MONTHNAME(TargetDate)) AS Description
FROM visits
INNER JOIN clientsites ON visits.ClientSiteFk = clientsites.ClientSitePk
LEFT OUTER JOIN pafaddresses ON clientsites.ActualPAF = pafaddresses.id
INNER JOIN Clients ON visits.ClientFk = Clients.ClientPk
WHERE (pafaddresses.CountryName !="England")
ORDER BY visits.TargetDate, visits.VisitStartDate
You can do that either with
WHERE (pafaddresses.CountryName != 'England' AND pafaddresses.CountryName != 'Wales')
or
WHERE pafaddresses.CountryName NOT IN ('England', 'Wales')
My query I'am quite sure that the easiest way will be to remove some select columns - well its a filter grid query so no idea if worth, for sure add a LIMIT 1
and the count would be on the index id, what do you think about it? Just to make it a smooth not a long executing query.
$fquery = $db->query("SELECT zlec_status.nazwa AS Status,
piorytet.nazwa AS Priorytet,
Concat(koord.imie, ' ', koord.nazwisko) AS `Koordynator`,
Concat(zlec_adresy.miasto, ' - ', zlec_adresy.ulica, ' ',
zlec_adresy.oddzial)
AS `adres`,
zlec_z_dnia,zlec_id,
zlec_nr,
zlec_do,
zlec_ogran,
awizacje,
awizacja_na_dzien,
termin_zamkniecia,
tresc,
uwagi
FROM zlec
INNER JOIN koord
ON zlec.koord = koord.id
INNER JOIN zlec_adresy
ON zlec.zlec_addres = zlec_adresy.id
INNER JOIN piorytet
ON zlec.priorytet = piorytet.id
INNER JOIN zlec_status
ON zlec.status_zlecenia = zlec_status.id
HAVING adres LIKE concat('%',:az,'%'), array(
"az" => array_values($activeFilters)[0]
));