MYSQL: left join in two tables using distinct value from one table - mysql

I want to join two tables having a common column stationcode(TABLE vfdefects & tempsubstation).
The problem is tempsubstation has duplicate column values while i only want the count of each unique values. With my current attempts it is doubling the value for duplicate entries using LEFT JOIN and GROUP BY
TABLE A
ID|stationID|CODE
TABLE B
A|B|C|D|stationcode
The query is as follows:
SELECT DISTINCT TS.substationid,'20130924',ts.employeeid,ts.substationcode,ts.manufacturingproductid,ts.assemblylineid,ts.teamid,ts.subofficecode,
TA.AllowID,ta.OtherAllowanceID,ta.allowname,ta.minbenchmark,ta.maxbenchmark,COUNT(vfd.DefectsID) Achieved
FROM tempsubstation ts
LEFT JOIN TempAllowances ta ON ts.manufacturingproductid=ta.manufacturingproductid AND ts.subofficecode=ta.subofficecode AND ta.teamid=ts.teamid
LEFT JOIN wms_assemblyqcmapping aqc ON ts.subofficeid=aqc.subofficeid AND ts.manufacturingproductid=aqc.manufacturingproductid AND ts.assemblylineid=aqc.assemblylineid
LEFT JOIN wms_vfdefects vfd ON vfd.QCStationCode=aqc.QCStationCode AND ts.SubstationCode =vfd.MFGStationNum AND DATE(vfd.CreationDate)='2013-09-24'
WHERE ta.AllowID=42
GROUP BY ta.minbenchmark,ta.maxbenchmark,ts.substationid
HAVING COUNT(vfd.DefectsID)>=ta.minbenchmark AND COUNT(vfd.DefectsID)<=ta.maxbenchmark

Change:
FROM tempsubstation ts
to:
FROM (SELECT * FROM tempsubstation
GROUP BY columnWithDuplicateValues) ts

How are you running the query? if via PHP then simplify the SQL and run a second SQL in the PHP read loop.

Related

How can I compare the sum of one field to another single field?

My data set is like so:
Total_Order_Table
Order_no (unique)
Shipped_quantity
Order_Detail_Table
Order_number (not unique)
Quantity_per_bundle
I need to take the sum of Quantity_per_bundle for each order_number from Order_Detail_Table and compare it to the Shipped_quantity.
My idea is an outer join so that my data will look like so:
I need to be able to see quantity discrepancies and if the order number exists in both tables.
Thanks in advance!
Normaly with a FULL OUTER JOIN in sql:
SELECT to.Order_no AS Order_no_Total_Order_Table, od.Order_number AS Order_No_Ordr_detail_Table, SUM(od.Order_number) AS sum_Quanitty_Per_Bundle, od.Order_number
FROM Total_Order_Table AS to
FULL OUTER JOIN Order_Detail_Table AS od ON to.Order_no = od.Order_number
GROUP BY to.Order_no
But FULL OUTER JOIN don't exist in mysql. But you can simulate it : http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/
Unless I'm missing something subtle in the question, isn't this just as simple as a SELECT query with a join between the tables.
Something along the lines of this should achieve the result:
SELECT tot.Order_no,
odt.Order_no,
SUM(odt.Quantity_per_bundle),
tot.Shipped_quantity
FROM Total_Order_Table tot
LEFT JOIN Order_Detail_Table odt ON odt.Order_Number = tot.Order_Number
GROUP BY tot.Order_no, odt.Order_no, tot.shipped_quantity
(Code not tested in MySQL so forgive errors)

Inner join without results from second table

I am trying to create an inner-join MySQL Query of two tables:
'swatchset'
->swatchset_id
->swatchset_name
'swatches'
->swatch_id
->swatch_name
->swatch_hex
->etc...
I currently have one record in the 'swatchset' table:
swatchset_id | swatchset_name
8 default
The 'swatches' table is empty.
I want to get as result the 'swatchset'.'swatchset_name'
I guess I don't understand INNER JOIN very well because this Query results nothing:
SELECT `swatchset`.`swatchset_name`, `swatches`.`swatch_id`, `swatches`.`swatch_name`, `swatches`.`swatch_hex`, `swatches`.`swatch_type` FROM `swatchset`
INNER JOIN `swatches`
ON `swatches`.`f_swatchset_id` = `swatchset`.`swatchset_id`
WHERE `swatchset`.`swatchset_id` = '8';
How can I get at least the found 'swatchset' row as result?
Left outer join will fill with nulls columns of second table when not found:
SELECT `swatchset`.`swatchset_name`, `swatches`.`swatch_id`, `swatches`.`swatch_name`, `swatches`.`swatch_hex`, `swatches`.`swatch_type` FROM `swatchset`
LEFT OUTER JOIN `swatches`
ON `swatches`.`f_swatchset_id` = `swatchset`.`swatchset_id`
WHERE `swatchset`.`swatchset_id` = '8';
inner join doesn't return entries from first table without matching ones in second table

Select only distinct values for a particular column mysql

We have two tables in mysql database.Screenshots are attached below.
Given table ads_testTable
here is the screenshot of my dimesnionvalue_flattable
We have to run a query like the one below.
SELECT Quiz_Attempt.L1_Key dimID,
Quiz_Attempt.L1_Label CatVars,
COALESCE(**xyz**,0) AS series0
FROM DSQ_ADSSCHEMA.ADS_TestTable dataTable
RIGHT OUTER JOIN LS_CONFIG.DSQ_DIMENSIONVALUES_FLAT Quiz_Attempt on dataTable.Quiz_Attempt = Quiz_Attempt.L1_Key
WHERE Quiz_Attempt.L0_Key = 'All Levels' AND
Quiz_Attempt.DimensionID = 'Packet'
GROUP BY Quiz_Attempt.L1_Key, Quiz_Attempt.L1_Label;
My motive is to write a query in place of xyz so that I can get avg of obtainedMarks column in testtable according to the value of dimID I get.Each distinct Quiz_Attempt is a different test so If a Packet is repeating for a particular Quiz_Attempt in testTable, it should take only one value for that AttemptID.
I think you query could take the form of:
SELECT
L1_Key dimID,
L1_Label CatVars,
COALESCE('**xyz**',0) AS series0
FROM (
SELECT *
FROM (SELECT * FROM ADS_TestTable GROUP BY ADS_TestTable.Quiz_Attempt) dataTable
RIGHT OUTER JOIN DSQ_DIMENSIONVALUES_FLAT Quiz_Attempt on dataTable.Quiz_Attempt = Quiz_Attempt.L1_Key
WHERE Quiz_Attempt.L0_Key = 'All Levels' AND
Quiz_Attempt.DimensionID = 'Packet'
GROUP BY dataTable.Quiz_Attempt
) A GROUP BY dimID, CatVars;
The JOIN is done in an inner query, and grouped by Quiz_Attempt, so that you get a single row per attempt. This result is then used to compute what you need.

My SQL JOIN query returning No results

SELECT 'nmc_cd.CDID','nmc_cd.CDTitle', 'nmc_cd.CDYear','nmc_cd.pubID','nmc_cd.catID','nmc_cd.CDPrice','nmc_category.catDesc'
From nmc_cd
JOIN nmc_category
ON 'nmc_cd.catID'='nmc_category.catID'
ORDER BY CDTitle
Ive been putting this query into mySQL to try and get a table with results from ncm_CD and nmc_category but it keeps retuning no value?? also if i use a right or left join it is returning the Column name (e.g. nmc_cd.CDJD)
Try removing the quotes so that you are referencing the column itself - with quotes, you are working with strings and not the columns.
SELECT nmc_cd.CDID, nmc_cd.CDTitle, nmc_cd.CDYear, nmc_cd.pubID, nmc_cd.catID, nmc_cd.CDPrice, nmc_category.catDesc
From nmc_cd
JOIN nmc_category
ON nmc_cd.catID = nmc_category.catID
ORDER BY CDTitle
Also, as #Randy mentions, make sure you actually have data that matches the criteria :)
I am not sure why you have single quotes around everything, a single quote is considered a static string value so it will not return the data from the columns:
SELECT nmc_cd.CDID,
nmc_cd.CDTitle,
nmc_cd.CDYear,
nmc_cd.pubID,
nmc_cd.catID,
nmc_cd.CDPrice,
nmc_category.catDesc
From nmc_cd
INNER JOIN nmc_category
ON nmc_cd.catID=nmc_category.catID
ORDER BY CDTitle
But with the INNER JOIN that you are using you have to be sure that you have values that match data in both tables, if you do not then no data will be returned. If you don't have data in both tables, then you will want to use either a LEFT JOIN or RIGHT JOIN:
SELECT nmc_cd.CDID,
nmc_cd.CDTitle,
nmc_cd.CDYear,
nmc_cd.pubID,
nmc_cd.catID,
nmc_cd.CDPrice,
nmc_category.catDesc
From nmc_cd
LEFT JOIN nmc_category
ON nmc_cd.catID=nmc_category.catID
ORDER BY CDTitle
MySQL uses backticks around columns and table names not single quotes, if you applied them then your query would look like this:
SELECT `nmc_cd`.`CDID`,
`nmc_cd`.`CDTitle`,
`nmc_cd`.`CDYear`,
`nmc_cd`.`pubID`,
`nmc_cd`.`catID`,
`nmc_cd`.`CDPrice`,
`nmc_category`.`catDesc`
From `nmc_cd`
JOIN `nmc_category`
ON `nmc_cd`.`catID`=`nmc_category`.`catID`
ORDER BY `CDTitle`

MYSQL get other table data in a join

I am currently running this SQL
SELECT jm_recipe.name, jm_recipe.slug
FROM jm_recipe
LEFT JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
WHERE jm_category_recipe.category_id = $cat"
This returns the desired results except that I also need to return the name of the category that the recipe I am looking for is in, to do this I tried to add the field in to my SELECT statement and also add the table into the FROM clause,
SELECT jm_recipe.name, jm_recipe.slug, jm_category_name
FROM jm_recipe, jm_category
LEFT JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
WHERE jm_category_recipe.category_id = $cat"
However this just returns no results, what am i doing wrong?
You need to join both tables:
SELECT jm_recipe.name, jm_recipe.slug, jm.category_name
FROM jm_recipe
INNER JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
INNER JOIN jm_category ON jm_recipe.recipe_id = jm_category.recipe_id
WHERE jm_category_recipe.category_id = $cat
I've changed the joins to inner joins as well. You might want to make them both LEFT joins if you have NULLs and want them in the result.
Also, you're vulnerable to SQL Injection by simply copying over $cat.
Here's some PHP specific info for you (I'm assuming you're using PHP.)