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
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'm new to MySQL and I'm trying to make the following pseudocode work:
SELECT IF(
EXISTS(SELECT * FROM users WHERE `email`="admin" AND `token`="blablabla"),
(UPDATE * FROM sometable WHERE `var`="notimportant"),
"NOT_AUTHORIZED");
What I'm trying to achieve is running code based on the presence of a row, and if it doesn't exists return a message, or something usable. If it does exists, run another SQL command instead, and return those results.
Is this possible?
Your intent is a bit hard to follow from the invalid syntax. But the gist of your question is that you can use a where clause:
UPDATE sometable
SET . . .
WHERE var = 'notimportant' AND
EXISTS (SELECT 1 FROM users WHERE email = 'admin' AND token = 'blablabla');
You can also represent this as a JOIN. Assuming the subquery returns at most one row:
UPDATE sometable t CROSS JOIN
(SELECT 1
FROM users
WHERE email = 'admin' AND token = 'blablabla'
LIMIT 1
) x
SET . . .
WHERE var = 'notimportant' ;
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.
Were are facing a big problem with string length control in SQL Server 2008.
A brief recap of our system:
import data in a persistent staging area from *.txt file (semicolon as separator), using bulk insert in SQL Server environment;
in PSA table all columns are varchar(MAX);
cleaning operations using insert statement based on a select with multiple where conditions.
The problem we deal with is on a single column type and length, in fact in data warehouse level it has to be numeric and its lengths must not exceed 13 digits.
The select is the following:
select cast(LTRIM(RTRIM(data_giacenza)) as numeric),
LTRIM(RTRIM(codice_socio)),
LTRIM(RTRIM(codice_gln)),
LTRIM(RTRIM(tipo_gln)),
LTRIM(RTRIM(codice_articolo_socio)),
LTRIM(RTRIM(codice_ean_prodotto)),
LTRIM(RTRIM(codice_ecat_prodotto)),
LTRIM(RTRIM(famiglia)),
LTRIM(RTRIM(marca)),
LTRIM(RTRIM(classificazione_liv_1)),
LTRIM(RTRIM(classificazione_liv_2)),
LTRIM(RTRIM(classificazione_liv_3)),
LTRIM(RTRIM(classificazione_liv_4)),
LTRIM(RTRIM(modello)),
LTRIM(RTRIM(descrizione_articolo)),
cast(LTRIM(RTRIM(giacenza)) as numeric),
cast(LTRIM(RTRIM(acquistato)) as numeric), 'X' FROM psa_stock a
where EXISTS
(
SELECT 0
FROM(
SELECT
data_giacenza
,codice_socio
,codice_gln
,codice_articolo_socio
FROM psa_stock
where
LEN(LTRIM(RTRIM(data_giacenza))) = 8 and LEN(LTRIM(RTRIM(codice_socio))) = 3
and LEN(LTRIM(RTRIM(codice_gln))) = 13 and LEN(LTRIM(RTRIM(tipo_gln))) = 3
and LEN(LTRIM(RTRIM(codice_articolo_socio))) <= 15
and (LEN(LTRIM(RTRIM(codice_ean_prodotto))) <= 13 or LEN(ISNULL(codice_ean_prodotto, '')) = 0)
and (LEN(LTRIM(RTRIM(codice_ecat_prodotto))) = 9 or LEN(ISNULL(codice_ecat_prodotto, '')) = 0)
and LEN(LTRIM(RTRIM(famiglia))) = 2
and (LEN(LTRIM(RTRIM(marca))) <= 20 or LEN(ISNULL(marca, '')) = 0)
and (LEN(LTRIM(RTRIM(modello))) <= 30 or LEN(ISNULL(modello, '')) = 0)
and (LEN(LTRIM(RTRIM(descrizione_articolo))) <= 50 or LEN(ISNULL(descrizione_articolo, '')) = 0)
and LEN(LTRIM(RTRIM(giacenza))) <= 5
and LEN(LTRIM(RTRIM(acquistato))) <= 5
and (LEN(LTRIM(RTRIM(classificazione_liv_1))) <= 15 or LEN(ISNULL(classificazione_liv_1, '')) = 0)
and (LEN(LTRIM(RTRIM(classificazione_liv_2))) <= 15 or LEN(ISNULL(classificazione_liv_2, '')) = 0)
and (LEN(LTRIM(RTRIM(classificazione_liv_3))) <= 15 or LEN(ISNULL(classificazione_liv_3, '')) = 0)
and (LEN(LTRIM(RTRIM(classificazione_liv_4))) <= 15 or LEN(ISNULL(classificazione_liv_4, '')) = 0)
and ISNUMERIC(ltrim(rtrim(REPLACE(data_giacenza, ' ', '')))) = 1
and ISNUMERIC(ltrim(rtrim(REPLACE(codice_gln, ' ', '')))) = 1
and ISNUMERIC(LTRIM(RTRIM(REPLACE(giacenza, ' ', '')))) = 1 and charindex(',', giacenza) = 0
and ISNUMERIC(LTRIM(RTRIM(REPLACE(acquistato, ' ', '')))) = 1
and ISNUMERIC(ltrim(rtrim(REPLACE(codice_ean_prodotto, ' ', '')))) = 1
and ISNUMERIC(ltrim(rtrim(REPLACE(codice_ecat_prodotto, ' ', '')))) = 1
and codice_socio in (select codice_socio from ana_socio)
and tipo_gln in (select tipo from ana_gln)
and codice_gln in (select codice_gln from dw_key_gln)
group by
data_giacenza
,codice_socio
,codice_gln
,codice_articolo_socio
having COUNT (*) = 1
) b
where
a.data_giacenza = b.data_giacenza and
a.codice_articolo_socio = b.codice_articolo_socio and
a.codice_socio = b.codice_socio and
a.codice_gln = b.codice_gln)
The critical field is codice_ean_prodotto.
In fact, it allows to consider also values as SEAGAT7636490026751,NE20000003039,NE20000002168 which are not numeric and, the first, overlap maximum dimensions.
As result, the insert statement gives back
String o binary data would be truncated
error and fails the insertion.
Thanks in advance! I look forward your help!!!
Enrico
Have you tried executing that query, and adding codice_ean_prodotto = 'NE20000003039' to the where clause? Be sure that these are the actual field that is giving you the problem. If the select returns a row with that where clause, then something's wrong with the logic.
I'm leaning towards your having COUNT (*) = 1 clause in the EXISTS subquery - is it possible to have more than one record for these specific keys? As long as your PK is made up of those 4 fields (data_giacenza, codice_articolo_socio, codice_socio, codice_gln), you shouldn't need the GROUP BY and HAVING clauses at all. If you're not joining on your primary key, it could be that it is the culprit.
It's hard to tell without seeing your data model, however.
I figured out what was wrong.
In the inner select, we were excluding from the selection all records not respecting format constraints and duplication (the meaning of count(*)=1), extracting only the PK of the destination table.
But when selecting with PK we retrieve also those record that were duplicates, but were excluded by the format constraint, leading the insert to error due to dimension issues.
Now I divided the steps:
Duplicates lookup and deletion
Selection with format constraints
It works!
select TO_CHAR(TRUNC(SYSDATE),'DD MONTH,YYYY'),a.appl_no,a.assigned_to,c.trading_name co_name, ' ' co_name2, d.bank_acct_no credit_acct_no, d.bank_no credit_bank_no, d.bank_branch_no credit_branch_no,a.service_id
from newappl a, newappl_hq b, newappl_ret c, newappl_ret_bank d where a.appl_no = c.appl_no and c.ret_id= d.ret_id and a.appl_no=(select appl_no from newappl where appl_no='224') and c.outlet_no in ('1','2') and rownum=1
Why the out put for above statment is only one row while I have 1 & 2 for following statement
select c.outlet_no from newappl_ret c where appl_no = '224'
its hard to say when you dont see data stored in db but try this one:
select c.outlet_no from mss_t_newappl_ret c where appl_no = 224
check if in the column appl_no there isnt any spacebar
maybe this?
and a.appl_no IN (select appl_no from newappl where appl_no='224')
or delete this expression
and rownum=1