Nesting a max(date) statement in a mysql INNER JOIN - mysql

I'm having difficult with the logic/syntax surrounding a nested 'select max(date)' style statement. Let me try to explain. I have three tables that my statement is pulling data from:
Table #1 (table1_companies)
[id, companyname, industry]
Table #2: (table2_companydata)
[id, companyname, data, date_added]
Table #3: (table3_watchlist)
[id, companyname, usernane]
The statement I'm attempting to execute takes a company name from the Table 3, INNER JOINS the 'industry' from Table 1 and then INNER JOINS the latest company info (based on the last date) from Table 2. It is Table 2 that can have many rows per company, I just need the last one based on the latest date that was added. My current (simplified) statement without the attempt to grab the last date is:
SELECT
table1_companies.industry,
table2_companydata.data,
table3_watchlist.*
FROM
table3_watchlist
INNER JOIN table1_companies ON table1_companies.companyname = table3_watchlist.companyname INNER JOIN table2_companydata ON table2_companydata.companyname = table3_watchlist.companyname WHERE username='username'");
I think I need to insert a "SELECT max(date_added) FROM table2_companydata" into the 2nd INNER JOIN. But I've had no success with either logic or syntax. Can any enlighten me?

Do the joins and then select the last record. Here is one method using a where clause for the logic:
SELECT c.industry, cd.data, w.*
FROM table3_watchlist w INNER JOIN
table1_companies c
ON c.companyname = w.companyname INNER JOIN
table2_companydata cd
ON cd.companyname = w.companyname
WHERE username = 'username' AND
cd.date_added = (select max(cd2.date_added)
from table2_companydata cd2
where cd2.companyname = cd.companyname
);

Related

Grouping method

I am working on a query with the following format:
I require all the columns from the Database 'A', while I only require the summed amount (sum(amount)) from the Database 'B'.
SELECT A.*, sum(B.CURTRXAM) as 'Current Transaction Amt'
FROM A
LEFT JOIN C
ON A.Schedule_Number = C.Schedule_Number
LEFT JOIN B
ON A.DOCNUMBR = B.DOCNUMBR
ON A.CUSTNMBR = B.CUSTNMBR
GROUP BY A
ORDER BY A.CUSTNMBR
My question is regarding the grouping statement, database A has about 12 columns and to group by each individually is tedious, is there a cleaner way to do this such as:
GROUP BY A
I am not sure if a simpler way exists as I am new to SQL, I have previously investigated GROUPING_ID statements but thats about it.
Any help on lumped methods of grouping would be helpful
Since the docnumber is the primary key - just use the following SQL:
SELECT A.*, sum(B.CURTRXAM) as 'Current Transaction Amt'
FROM A
LEFT JOIN C
ON A.Schedule_Number = C.Schedule_Number
LEFT JOIN B
ON A.DOCNUMBR = B.DOCNUMBR
ORDER BY RM20401.CUSTNMBR
GROUP BY A.DOCNUMBR

Appending rows returned from different queries into one

I am having 3 queries, which takes data from 3 different tables (with joins) and their column names are pretty much same (or I made them same by using ASkeyword). Once the 3 queries are completed, I want to combine their results, so it looks like they are coming from one table. Please have a look at the below codes.
1st Query
SELECT Client_Portfolio.*,
Client.Name,
Provider.Name,
"One" AS Income_Type,
One.`One_Gross_Fee` AS "Gross_Fee",
One.`One_V_Fee` AS "V_Fee",
One.`One_E_Fee` AS "E_Fee",
One.`One_I_Fee` AS "I_Fee",
One.`One_Tax_Provision` AS "Tax_Provision",
One.`One_Net_Income` AS "Net_Income",
"N/A" AS VAT,
One.`Updated_Date`
FROM Client_Portfolio
INNER JOIN Portfolio ON Portfolio.`idPortfolio` = Client_Portfolio.`idPortfolio`
INNER JOIN Client ON Client.idClient = Client_Portfolio.idClient
JOIN Provider ON Provider.idProvider = Portfolio.idProvider
INNER JOIN One ON One.idPortfolio = Portfolio.idPortfolio
2nd Query
SELECT Client_Portfolio.*,
Client.Name,
Provider.Name,
"Two" AS Income_Type,
Two.`Two_Gross_Fee` AS "Gross_Fee",
Two.`Two_V_Fee` AS "V_Fee",
Two.`Two_E_Fee` AS "E_Fee",
Two.`Two_I_Fee` AS "I_Fee",
Two.`Two_Tax_Provision` AS "Tax_Provision",
Two.`Two_Net_Income` AS "Net_Income",
Two.`Two_Vat` AS VAT,
Two.`Updated_Date`
FROM Client_Portfolio
INNER JOIN Portfolio ON Portfolio.`idPortfolio` = Client_Portfolio.`idPortfolio`
INNER JOIN Client ON Client.idClient = Client_Portfolio.idClient
JOIN Provider ON Provider.idProvider = Portfolio.idProvider
INNER JOIN Two ON Two.idPortfolio = Portfolio.idPortfolio
3rd Query
SELECT Client_Portfolio.*,
Client.Name,
Provider.Name,
"Three" AS Income_Type,
Three.`Three_Gross_Fee` AS "Gross_Fee",
"N\A" AS "V_Fee",
Three.`Three_E_Fee` AS "E_Fee",
"N\A" AS "I_Fee",
Three.`Three_Tax_Provision` AS "Tax_Provision",
Three.`Three_Net_Income` AS "Net_Income",
Three.`Three_Vat` AS VAT,
Three.`Updated_Date`
FROM Client_Portfolio
INNER JOIN Portfolio ON Portfolio.`idPortfolio` = Client_Portfolio.`idPortfolio`
INNER JOIN Client ON Client.idClient = Client_Portfolio.idClient
JOIN Provider ON Provider.idProvider = Portfolio.idProvider
INNER JOIN Three ON Three.idPortfolio = Portfolio.idPortfolio
Once these queries are done, I want to combine their results. Which means, Rows returned by the 2nd Query will be appended after the rows returned by the 1st query. Rows returned by the 3rd query will be appended after the rows returned by the 2nd query. Finally, I want to sort the final result by Updated_Date
How can I do this?
Use UNION to combine the queries:
SELECT one_fields FROM Client_Portfolio ...
UNION
SELECT two_fields FROM Client_Portfolio ...
UNION
SELECT three_fields FROM Client_Portfolio ...
Sorting can be done by appending an order by clause after the last query, as follows:
SELECT one_fields FROM Client_Portfolio ...
UNION
SELECT two_fields FROM Client_Portfolio ...
UNION
SELECT three_fields FROM Client_Portfolio ...
ORDER BY field1, field2, field3...;
Note that field1, field2... can be field names or field numbers (starting from 1).

Need mysql query to pull data from two tables

So after helpful feedback from my original question, I now have this query:
SELECT sessions.id, sessions.title, sessions.abstract, sessions.presenters, sessions.proposal_id, proposals.outcomes, proposals.CategorySelection, proposals.research3, proposals.research4, proposals.research5, proposals.research6, proposals.innovation3, proposals.innovation4, proposals.innovation5,proposals.innovation6, proposals.application3, proposals.application4, proposals.application5, proposals.application6, proposals.integration3, proposals.integration4, proposals.integration5, proposals.integration6, proposals.references, proposals.organization
FROM sessions, proposals
INNER JOIN proposals ON proposals.id = sessions.proposal_id
WHERE sessions.id = '$id
LIMIT 1;)
that is getting me nowhere fast. What am I doing wrong?
Original question:
I need to pull several fields from one table and several more from a second table. The criteria is that a field called proposal_id match the id field of the second table. I am fairly new so this is what I have so far. It is not working, but not sure how to make it work.
(SELECT `title`,`abstract`,`presenters`,`proposal_id` FROM `sessions` WHERE `id`='$id')
UNION
(SELECT `outcomes`,`CategorySelection`,`research3`,`research4`,`research5`,`research6`,`innovation3`,`innovation4`,`innovation5`,
`innovation6`,`application3`,`application4`,`application5`,`application6`,`integration3`,`integration4`,`integration5`,`integration6`,`references`,`organization` FROM `proposals` WHERE `id`= `sessions`.`proposal_id`)
LIMIT 1;
You need to use JOIN not UNION
select
s.*,p.*
from `sessions` s
inner join `proposals` p on p.id = s.proposal_id
where s.id = '$id'
This is how you can join both the tables using the common key between.
You can select the specific fields instead of .* by specifying the column names as
s.col1,s.col2,p.col1,p.col2
etc
Try to use JOINS, where you can match the related fields from both the tables , this is the most convenient way to fetch records from multiple tables
UNION is used when you want to combine two queries
select a.id,b.some_field from table1 as a
INNER JOIN table2 as b ON b.prospal_id = a.id

Mysql: Unable to fetch value from a select query inside a query

I have the following query. If I run it I get this error message.
Query-
SELECT account_name,ABC,date FROM entries
LEFT JOIN accounts ON accounts.id = entries.accounts_id
LEFT JOIN voucher ON voucher.id = entries.trans_id
WHERE trans_id IN ( SELECT trans_id, amount AS ABC FROM entries
WHERE accounts_id='$accounts_id' AND side='C')
AND accounts_id!='$accounts_id' AND side='D'
AND voucher.date between '$dateragne1' AND '$dateragne2'
I think the problem is with the value ABC. It is unable to fetch the value from the second query.
Could you please tell me how to fix this query?
Thanks in Advance :)
Try this:
SELECT account_name, _inner.ABC, date
FROM
(
SELECT amount AS ABC FROM entries
WHERE accounts_id='$accounts_id' AND side='C'
) AS _inner, entries
LEFT JOIN accounts ON accounts.id = entries.accounts_id
LEFT JOIN voucher ON voucher.id = entries.trans_id
WHERE trans_id IN
(
SELECT trans_id FROM entries WHERE accounts_id='$accounts_id' AND side='C'
)
AND accounts_id!='$accounts_id' AND side='D'
AND voucher.date between '$dateragne1' AND '$dateragne2'`
Notes:
Using subquery like this doesn't allow you to request a fields from it.
Also, IN statement use data from only only column, not two.

How do I create a 3-way LEFT JOIN with MYSQL?

I'm attempting to create a 3-way LEFT JOIN using MYSQL and I'm having difficulty accomplishing it so I figured this would be the place to figure it out.
I have a three tables as I'll display below. The first contains a list of items that a user has added to their queue to be processed by the game. The other two contain details about each of the items such as their strengths, points to completion, etc. In the queued table, I have two types of items, units and research. The unit details are found in table 2 and the research details are found in table 3.
Table 1: The first table (core_queued_units) contains the following fields: id, unit_id, name, location, class(unit or research),sort.
Table 2: The second table (core_available_units) contains the following fields: id, name, description, etc.
Table 3: The third table (core_available_tech) contains the following fields: id, name, description, etc.
FROM core_queued_units
LEFT JOIN core_available_units
ON core_queued_units.unit_id = core_available_units.id
AND core_queued_units.class='Unit'
LEFT JOIN core_available_tech
ON core_queued_units.unit_id = core_available_tech.id
AND core_queued_units.class='Research'
WHERE core_queued_units.location = '1'
AND core_queued_units.user_id ='".$GLOBALS['self']['usrID']."'
ORDER BY core_queued_units.sort ASC
If fields in core_available_units and core_available_tech are equal, you can try this:
SELECT *
FROM core_queued_units cq
LEFT JOIN (
select cau.*, 'Unit' class from core_available_units cau
union all
select cat.*, 'Research' class from core_available_tech cat) c
ON cq.unit_id = c.unit_id and c.class = cq.class
WHERE cq.location = '1'
AND cq.user_id ='".$GLOBALS['self']['usrID']."'
ORDER BY cq.sort ASC
If you are trying to join multiple tables, you can do as follows. I am taking Table1 as base table.
SELECT columnname1, columnname2......
FROM Table1
LEFT OUTER JOIN Table2 ON Table1.PK = Table2.FK (here Table2.FK is the Primary key of Table1 which is used as Foreign key in Table2)
LEFT OUTER JOIN Table3 ON Table1.PK = Table3.FK (same condition as above)
WHERE insert your conditions here
using this sample, columns from Table2 & Table3 will added at the right most side of Table1.
Please inform if this helps.
Can you try to swap the arguments in the On-clause
core_queued_units.unit_id = core_available_tech.id?