简体   繁体   中英

Join two tables and get the latest date.

Im new to this form and hopefuly I can get some awesome help!

I got three tables

1 "companies"
  ID 

2 "log"
  compid
  datum (date)

3 "sales" 
  datumnow (datetime)
  uppdaterad (datetime)

I want to compare log and sales and get the latest or the "newest" entry and display a ASC list of companies from table 1 with only one company for each row. (comparing datum, datumnow & uppdaterad and get the highest date value displayed on one row for each ID from companies)

#RESULT 
Rover - 2012-01-15
Daniel - 2012-02-01
Damien - 2012-03-05

I´ve struggled with this for a few days now and can´t get a hold of the solution. App. ANY help! thanx.

You can use GREATEST() to return the most recent date from those three columns. This assumes you have another column in sales that relates to the other tables. From the structure you show above, the relationship is unclear.

SELECT
  companies.ID,
  GREATEST(log.datum, sales.datumnow, sales.uppdatedad) AS mostrecent
FROM
  companies LEFT JOIN log ON companies.ID = log.compid
  /* Assumes sales also has a compid column.  Will edit if new info is posted */
  LEFT JOIN sales ON companies.ID = sales.compid
WHERE log.userid='$userID' AND sales.seller='$userID'

For only one row with the max date per company, use a MAX() aggregate with a GROUP BY :

SELECT
  companies.ID,
  MAX(GREATEST(log.datum, sales.datumnow, sales.uppdatedad)) AS mostrecent
FROM
  companies LEFT JOIN log ON companies.ID = log.compid
  /* Assumes sales also has a compid column.  Will edit if new info is posted */
  LEFT JOIN sales ON companies.ID = sales.compid
WHERE log.userid='$userID' AND sales.seller='$userID'
GROUP BY companies.ID

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