My SQL JOIN query returning No results - mysql

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`

Related

MAX(Date) is giving empty result

I have a table with exchange rate like below
And I am using the maxofdate to pick all these values based on currency code. But the query is giving blank.
Select USDAMOUNT * dbo.EXCHANGERATEAMT
from dbo.Amount_monthly
Left Join dbo.EXCHANGERATE on dbo.Amount_monthly.Currencycode=dbo.EXCHANGERATE.fromcurrencycode
WHERE ValidToDateTime = (Select MAX(ValidToDateTime) from dbo.EXCHANGERATE)
AND dbo.EXCHANGERATE.EXCHANGERATETYPECODE = 'DAY'
Using this statement
CONVERT(DATE,ValidToDateTime) = CONVERT(DATE,GETDATE()-1)
instead of subquery is giving me expected result.
Can someone correct this.
thanks in advance.
If I understand correctly, you need two things. First, the condition for the max() needs to match the condition in the outer query. Second, if you really want a left join, then conditions on the second table need to go in the on clause.
The resulting query looks like:
Select . . .
from dbo.Amount_monthly am Left Join
dbo.EXCHANGERATE er
on am.Currencycode = er.fromcurrencycode and
er.ValidToDateTime = (Select max(er2.ValidToDateTime)
from dbo.EXCHANGERATE er2
where er2.EXCHANGERATETYPECODE = 'DAY'
) and
er.EXCHANGERATETYPECODE = 'DAY';
I would write this using window functions, but that is a separate issue.
Try removing WHERE clause for ValidToDateTime and include it in the JOIN as AND condition
SELECT USDAMOUNT * dbo.EXCHANGERATEAMT
FROM dbo.Amount_monthly
LEFT JOIN dbo.EXCHANGERATE
ON dbo.Amount_monthly.Currencycode = dbo.EXCHANGERATE.fromcurrencycode
AND ValidToDateTime = (SELECT MAX(ValidToDateTime) --remove WHERE clause
FROM dbo.EXCHANGERATE)
AND dbo.EXCHANGERATE.EXCHANGERATETYPECODE = 'DAY';
I cleaned up your query a bit: as the other folks mentioned you needed to close the parentheses around the MAX(Date) sub-query, and if you reference a LEFT JOINed table in the WHERE clause, it behaves like an INNER JOIN, so I changed to in INNER. You also had "dbo" sprinkled in as a field prefix, but that (the namespace) only prefixes a database, not a field. I added the IS NOT NULL check just to avoid SQL giving the "null values were eliminated" SQL warning. I used the aliases "am" for the first table and "er" for the 2nd, which makes it more readable:
SELECT am.USDAMOUNT * er.EXCHANGERATEAMT
FROM dbo.Amount_monthly am
JOIN dbo.EXCHANGERATE er
ON am.Currencycode = er.fromcurrencycode
WHERE er.ValidToDateTime = (SELECT MAX(ValidToDateTime) FROM dbo.EXCHANGERATE WHERE ValidToDateTime IS NOT NULL)
AND er.EXCHANGERATETYPECODE = 'DAY'
If you're paranoid like I am, you might also want to make sure the exchange rate is not zero to avoid a divide-by-zero error.

How to sum all elements in an indexed table

I tried to make a query to my database with this structure: Data Base Structure
I did this query:
SELECT partido.acronimoPartido, SUM(votosacta.numVotos) FROM partido, votosacta WHERE votosacta.partido_idpartido=1 AND partido.idpartido=1
This query does work like I want but displays only the SUM of 'votos' for idpartido=1
I want to be able to sum numVotos from 'votosacta' table for each member of my 'partido' table indexed in 'votosacta' but I seem to not be able to get the right sintax.
I tried something like this:
SELECT partido.acronimoPartido, SUM(votosacta.numVotos) FROM partido, votosacta WHERE votosacta.partido_idpartido = partido.idpartido
You need a group by clause:
select p.acronimoPartido,
SUM(v.numVotos)
from partido p
join votosacta v on v.partido_idpartido = p.idpartido
group by p.acronimoPartido
Also, use explicit join syntax instead of old comma based syntax and use aliases to make your queries concise and readable.

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

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.

sql left join for two tables using a CONCAT string as the argument

I need to get a title from table 2, table 2 has title and id column.
Table 1 has some data and three of these columns concatenated together makeup the id that can be found in table 1.
I used CONCAT_WS() function and gave this column an alias name and need to use the Alias for the on argument(At least this is what I understood I needed to do)
I thought this could be a simple left join, yet it is not working for me.
This is my query
SELECT
table_openers.mail,
table_openers.f_name,
table_openers.l_name,
table_openers.Quality,
CONCAT_WS('-',
table_openers.esp,
table_openers.acc,
table_openers.group) as 't1aid',
table_groups.aid,
table_groups.group_name
FROM
lance_mailstats.table_openers
LEFT JOIN
lance_mailstats.table_groups ON table_groups.aid = t1aid;
I get results for mail, f_name, l_name, Quality and t1aid, but the aid and group_name columns of the second table return null.
I feel like you can't use an alias in the ON clause.
Try doing
LEFT JOIN
lance_mailstats.table_groups ON table_groups.aid = CONCAT_WS('-',
table_openers.esp,
table_openers.acc,
table_openers.group);
"You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column" (from dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html).
And "The conditional_expr used with ON is any conditional expression of the form that can be used in a WHERE clause" (from dev.mysql.com/doc/refman/5.1/en/join.html).
So as a logical inference you're not allowed to use aliases in ON clauses.
try to use a subquery..
it goes like this.........
ex.
SELECT
tbl1.mail, tbl1.f_name, tbl1.l_name,tbl1.Quality, tbl1.t1aid,table_groups.aid,
table_groups.group_name
FROM
(SELECT
table_openers.mail,
table_openers.f_name,
table_openers.l_name,
table_openers.Quality,
CONCAT_WS('-',
table_openers.esp,
table_openers.acc,
table_openers.group) as 't1aid',
FROM
lance_mailstats.table_openers )tbl1
LEFT JOIN
lance_mailstats.table_groups ON table_groups.aid = tbl1.t1aid;

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.)