简体   繁体   中英

Php query 2 mysql tables with dates BETWEEN and multiple clauses

I have 2 tables named Receipts and Materials_Receipts_Markup

I am needing to query these mysql tables between specific user input dates from a form and as well as a condition that will search for all dates from a specific user (techID) from both tables. I having a tough go at it so far and don't think I am even close. Here's what I have so far

"SELECT Receipts.TechID, Receipts.TotalPrice, Receipts.TotalProfit,
Receipts.Date, Materials_Receipts_Markup.Markup, 
Materials_Receipts_Markup.DateOfReceipt,
Materials_Receipts_Markup.TechID".

"FROM Receipts, Materials_Receipts_Markup".

"WHERE Receipts.Date BETWEEN '$newStartDate' AND '$newEndDate' AND WHERE
Materials_Receipts_Markup.DateOfReceipt BETWEEN '$newStartDate' AND
'$newEndDate'".

"AND Receipts.TechID AND Materials_Receipts_Markup.TechID ='$FormTechID' ";

$newStartDate and $newEndDate are dates such as 2019-06-23

my sql skills aren't up to par yet for something this complicated. Any help would be appreciated

I think you want to use an OR to search each table separated, and get both TechID using = operator like :

WHERE 
(
    (Receipts.Date BETWEEN '$newStartDate' AND '$newEndDate') 
    OR
    (Materials_Receipts_Markup.DateOfReceipt BETWEEN '$newStartDate' AND '$newEndDate') 
)
AND Receipts.TechID = Materials_Receipts_Markup.TechID AND Receipts.TechID ='$FormTechID'

Unless there is another linking field between the two tables, there does not seem to be any logical connection between them, other than the data is entered by the same TechID. Instead of a JOIN, you may need a UNION instead

  select r.techid as tech, r.date as date, r.totalprice as price, r.totalprofit as profit, null as markup  
    from receipts r 
    where r.TechID = 'FormTechID' and r.date between '$newStartDate' AND '$newEndDate'

  UNION

  select mrm.TechID as tech, mrm.DateOfReceipt as date, null as price, null as profit,   mrm.markup as markup
    from Materials_Receipts_Markup mrm
    where mrm.TechID = '$FormTechID' and mrm.DateOfReceipt between '$newStartDate' AND '$newEndDate'

If there is some other field (such as ReceiptID), then you need to join your tables on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM