Problems with a LEFT JOIN - mysql

I'm trying to do a left join in two tables, the principal one is a table with production orders and the other one contains the quantity of defective material in those production orders. It is possible to have more than one different type of defect in one production order, so that means more than one register in the second table for one production order. The relations between table are the field production order, machine, production phase, article and enterprise:
SELECT PM.FECHA_FABRICACION,
--TRUNC(PM.FECHA_FABRICACION) AS FECHA,
PM.ORDEN_DE_FABRICACION,
PM.CODIGO_FAMILIA,
PM.CODIGO_ARTICULO,
PM.COD_MAQUINA,
DECODE (PM.COD_MAQUINA,'AN001','ANODIZADO', 'GR001','ANODIZADO', 'ES001','ANODIZADO','PU001', 'ANODIZADO', 'ZZ141', 'ANODIZADO', PM.COD_MAQUINA) AS MAQUINA_PARTE,
PM.DESC_MAQUINA,
PM.CANTIDAD_ACEPTADA,
PM.M2_ACEPTADOS,
PM.M2_CONPEPTO,
PM.M2_TOTAL,
PM.M2_EXT,
PM.KILOS_ACEPTADOS,
PM.BARRAS_ACEPTADAS,
PM.FASE_REALIZADA,
PR.CODIGO_DEFECTO,
PR.CANTIDAD_RECHAZADA,
PR.LONGITUD,
PR.KILOS_RECHAZADOS,
PR.OBSERVACIONES
FROM ST_VW_PRODUCCION_MAQUINAS PM
LEFT JOIN P_INFO_RECHAZOS PR
ON PM.CODIGO_EMPRESA = PR.CODIGO_EMPRESA
AND PM.ORDEN_DE_FABRICACION = PR.ORDEN_DE_FABRICACION
AND PM.CODIGO_ARTICULO = PR.CODIGO_ARTICULO
AND PM.COD_MAQUINA = PR.CODIGO_MAQUINA
AND PM.FASE_REALIZADA = PR.FASE
AND PM.CODIGO_EMPRESA = '01'
AND PM.FECHA_FABRICACION > TO_DATE('04/07/2022 00:00:00', 'DD/MM/YYYY HH24:MI:SS')
--AND TRUNC(PM.FECHA_FABRICACION) = TRUNC(PR.FECHA_RECHAZO);
However it's not working

If you are specifically looking for rejections, you dont need a LEFT JOIN, but a normal INNER JOIN, meaning you ONLY WANT to see those projects where at least one, or more, rejections had occurred.
The query itself looks ok otherwise, just get rid of the LEFT clause of left join.
As for the function DECODE, that is using PM.COD_MAQUINA at both the begin and end of the list of codes. Dont know if that was intentional.
For date filtering, if you are only looking for a specific date without regard to any time portion, you could change it to YYYY-MM-DD format without using the TO_DATE() construct as in
AND PM.FECHA_FABRICACION > '2022-07-04'
If you still are getting errors, please EDIT your post and provide what the error message is.

To explain further, you are using a LEFT JOIN, which is a type of outer join. An outer join means that all the results from one side that don't match will still be displayed, and will just be matched to null. In your case, production orders that aren't defective will be listed.
However, it seems that you want to only display results that match on both sides (production orders that do have defects). When you just JOIN then you will have the result you want.
Here's a helpful diagram

Related

Filtering SQL results by date

Here is my query for a maintenance dates list.
SELECT `checkdates`.`checkdateplanneddate`, `checkdates`.`checkdatevehicle`, `checktypes`.`checktype`, `checktypes`.`emailto`, `checktypes`.`daysnotice`
FROM `checkdates`
, `checktypes`
WHERE `checktypes`.`checktype` = `checkdates`.`checkdatechecktype`;
The idea is..
Everyday the server will email customers to let them know which checkdates are coming, based on the days notice that is set for that type of check. (see image)
Currently it is showing all checkdates.
All i need to do is filter the list so it only shows the dates that are
"Todays date plus checktypes.daysnotice"
I have tried many different queries, but cannot seem to get the right combo.
Thank you in advance
I have attached an image to show that the data is available
If I understand your question correctly, and assuming that you are running MySQL (as the use of backticks for quoting and the phpmyadmin screen copy indicate), you can use date arithmetics as follows:
SELECT cd.checkdateplanneddate, cd.checkdatevehicle, ct.checktype, ct.emailto, ct.daysnotice
FROM checkdates cd
INNER JOIN checktypes ct ON ct.checktype = cd.checkdatechecktype
WHERE cd.checkdateplanneddate = current_date + interval ct.daysnotice day
The where condition implements the desired logic.
Side notes:
Use standard, explicit joins! Implicit joins (with commas in the from clause) is a very old syntax, that should not be used in new code
Table aliases make the query easier to write and read

A better way to select from multiple rows of the same column in a joined table

My query is currently working, it just seems to me there is an easier/better way to get the same result. But my knowlegde is limited to basic SELECT,UPDATE,INSERT and DELETE queries with the occasional LEFT JOIN (as I understand the basics for linking the other table and fetching the data from that 2nd/3th/.. table.)
It is for a PHP page that will list machines, I'm trying to use 1 prepared query to generate all the info I need for the list and avoid queries within the loop if results.
For the question I'll limit it to just the involved data.
There are multiple languages, English as main/default, each machine can have up to 4 tags with some specifications.
The 3 tables involved are:
the machine_list, containing the machine_id and some basic info that isn't language specific, also not relevant for now.
the specification_list, containging specification_id,machine_id, lang, specification_value. specification_id links to the specification table with the name of the specification in all the used languages e.g. width, model, number of gears etc. (not relevant for this case), machine_id to link to the machine, lang to link to the language. and spefication_value holds the value of the specification e.g. 300mm,T1000,4 gears etc. Some specifications are translated, but some values would be the same for all.
the machine_tags with tag1,tag2,tag3,tag4,machine_id. tag1-4 can hold the specification_id or 0 if not linked.
For my list I want to show the general info + up to 4 tags, if the tags are available in the language, show it in that language. And the tags are to be shown in the order set.
This is my current query:
SELECT m.machine_id, t1.spec_value,t2.spec_value,t3.spec_value,t4.spec_value,t1e.spec_value,t2e.spec_value,t3e.spec_value,t4e.spec_value
FROM machine_list as m
LEFT JOIN machine_tags as t ON m.machine_id=t.machine_id
LEFT JOIN machine_specifications as t1 ON m.machine_id=t1.machine_id AND t.tag1=t1.spec_id AND t1.lang = ?
LEFT JOIN machine_specifications as t2 ON m.machine_id=t2.machine_id AND t.tag2=t2.spec_id AND t2.lang = ?
LEFT JOIN machine_specifications as t3 ON m.machine_id=t3.machine_id AND t.tag3=t3.spec_id AND t3.lang = ?
LEFT JOIN machine_specifications as t4 ON m.machine_id=t4.machine_id AND t.tag4=t4.spec_id AND t4.lang = ?
LEFT JOIN machine_specifications as t1e ON m.machine_id=t1e.machine_id AND t.tag1=t1e.spec_id AND t1e.lang = 'en'
LEFT JOIN machine_specifications as t2e ON m.machine_id=t2e.machine_id AND t.tag2=t2e.spec_id AND t2e.lang = 'en'
LEFT JOIN machine_specifications as t3e ON m.machine_id=t3e.machine_id AND t.tag3=t3e.spec_id AND t3e.lang = 'en'
LEFT JOIN machine_specifications as t4e ON m.machine_id=t4e.machine_id AND t.tag4=t4e.spec_id AND t4e.lang = 'en'
WHERE m.active = 1 ORDER BY m.list_date DESC
This is used in a prepared statement, loop the fetch and show the list. using the php code to show the tag if linked and show the text in the right language if the text is available.
As said, it works but I feel there might be a better way, it feels wrong to add 2 alias of the same table for each value I need. And for example I know that I now fetch 4 columns that we are not going to use, but I lack the knowledge to filter this out on the SQL side -> or if that is even a good idea. I expect around 300 active machines max, maybe in a couple of years the total list would be 1000+, I don't know if this has effect on possible solutions (with performance impact in mind)
Also with possible changes in the future in mind, like what if instead of 4 we want to show 5 tags. In it's current form I need to add 2 more aliasses to the query.
The current machine_tags table might not be a good fit for this, I can imagine a different setup with machine_id, specification_id, order and then have a max of 4 rows per machine could work as well. But I don't see (as in lack of knowledge) a lot of change in how I would fetch the specification values, I think I might need more joins for the 4 rows instead of the 1 for 4 columns.
Here is a sqlfiddle: http://sqlfiddle.com/#!9/86a824/1
In there i've added the query that would go on the dutch language (nl) and added aliasses to the selected values (In the prepared php statement I bind them to variables so for me they were already different)

A SQL query retrieve same line several time

I create a web page to display information from a database. The recovered data comes from five different tables. However, the SQL query sends the same line several times (5900 lines in the DB, 24000 on the page).
I tried with the classic JOIN, LEFT JOIN and LEFT OUTER JOIN but I still get the same result.
Here is my MySQL query:
SELECT
vs.Nom_VS,
vs.IP_VS,
vs.Port_VS,
f5.Cluster_F5,
pa.Nom_partition,
po.Nom_pool,
me.IP_membre,
Port_membre
FROM VS_F5 vs
JOIN F5 f5 ON (f5.id_F5 = vs.id_F5)
JOIN Partition pa ON (pa.id_partition = vs.id_partition)
JOIN Pool po ON (po.id_pool = vs.id_pool_pool)
JOIN Membres_F5 me ON (me.id_pool_pool = vs.id_pool_pool)
As I said, I retrieve 24000 lines while the DB only contains 5900 lines. I really don't understand why I get the same result with different JOIN.
Hope you can help (and sorry if this is a stupid mistake).
Ok that was just a problem in the db. Sorry

MultipleObjectsReturned error in django admin - but there is no duplication in database

I'm having a problem in the Django admin. I'm using version 1.5.5
I have a Booth model which has a foreign key to my AreaLayout model, which then goes back through another few models with foreign and many2many keys. My model code can be seen on pastebin. The initial indication of the problem in admin is that AreaLayouts are being duplicated in the select dropdown in Booth admin. The MultipleObjectsReturned error (traceback) is being raised when I then try to save a new booth. I was able to trace this back to the SQL query that django is creating to grab the AreaLayout list:
SELECT `venue_arealayout`.`id`, `venue_arealayout`.`name`, `venue_arealayout`.`description`, `venue_arealayout`.`area_id`, `venue_arealayout`.`additional_notes`
FROM `venue_arealayout`
INNER JOIN `venue_area` ON (`venue_arealayout`.`area_id` = `venue_area`.`id`)
INNER JOIN `venue_venue` ON (`venue_area`.`venue_id` = `venue_venue`.`id`)
INNER JOIN `venue_venue_venue_type` ON (`venue_venue`.`id` = `venue_venue_venue_type`.`venue_id`)
INNER JOIN `venue_venuetype` ON (`venue_venue_venue_type`.`venuetype_id` = `venue_venuetype`.`id`)
WHERE (`venue_arealayout`.`id` = 66 )
This query produces a duplicate in MySQL when I run it there. Removing the final 2 JOINs results in a single result being returned (which is the desired result), whereas removing only the last join still results in duplication.
I tried running that query with SELECT * in place of selecting specific fields and the two results in that case are almost equal. The difference is that the venue in question has multiple venuetypes and I'm getting a result for each of those. Is there any way I can tell django not to include those joins for these queries, or is there a way I can get distinct results as far as AreaLayouts go?
I think you're being caught by the bug reported in ticket 11707. One of the comments mentions that it can cause a MultipleObjectsReturned exception.
All I can suggest is that you stop using limit_choices_to. Your models are fairly complex, so I can't immediately see which one is causing the problem.

PHP Heatmap - Large Value difference

Hi I have this Query and I'm getting an empty result, Anyone see anything obviously wrong with this?
SET SQL_BIG_SELECTS=1;
SELECT sector, SUM((fleetnow)+(fleetsoon)) AS Count
FROM AEDatabase
INNER JOIN AEPlayer AS Own ON AEDatabase.owner = Own.id
INNER JOIN AEPlayer AS Occ ON AEDatabase.occer = Occ.id
WHERE Galaxy='L49' AND (Own.guild='1085' OR Occ.guild='1085')
GROUP BY sector
Specific message from MySQL is:
"MySQL returned an empty result set (i.e. zero rows). ( Query took 0.4441 sec )"
Thanks for any help anyone can give.
If SQL request is composed correctly according to your business logic, and it returns no data it means, that either AEPlayer doesn't contain related data or AEDatabase doesn't contain any data related to Galaxy='L49'
You should separate all components of your request to determine what exactly collapses the result set.