SELECT a.price as price1 , IFNULL(b.price,'(no data)') as price2 , (a.price - IFNULL(b.price,0)) as difference FROM table1 a LEFT JOIN table2 b ON (a.`item name` = b.`item name`) GROUP BY a.`item name` HAVING IFNULL(b.`date`,'') = MAX(IFNULL(b.`date`,'')
Here's how it works.
He selects data from 2 tables: all data from table 1 and the corresponding data from table2.
If he cannot find the corresponding data from table2, he will replace the null
values ββinstead of the missing rows. ( left join
)
It then groups the ( group by
) rows based on table1.item name
.
This concatenates several lines per element.
The having
corrects this only by selecting the newest date strings from table2.
A small amendment is built into the select
and having
clauses to deal with the case where there is no data in table 2 to match table1.
Your request should be:
SELECT s.closing as price1 , IFNULL(sh.closing,'(no data)') as price2 , (s.closing - IFNULL(sh.closing,0)) as difference FROM stocks s LEFT JOIN stockhistory sh ON (s.symbol = sh.symbol) GROUP BY s.symbol HAVING IFNULL(sh.edate,'') = MAX(IFNULL(sh.edate,'') LIMIT 30 OFFSET 0;
Johan source share