问题
I have two table account and balance
/---------------------\
| cid | name | mobile |
|---------------------|
| 1 | ABC | 12345 |
|---------------------|
| 2 | XYZ | 98475 |
\---------------------/
/----------------------------\
| date | cid | balance |
|----------------------------|
| 2013-09-19 | 1 | 5000 |
|----------------------------|
| 2013-09-19 | 2 | 7000 |
|----------------------------|
| 2013-09-20 | 1 | 300 |
|----------------------------|
| 2013-09-20 | 2 | 4500 |
|----------------------------|
| 2013-09-21 | 2 | 600 |
\----------------------------/
I would like to join this two table and get the balance of the maximum date for a particular cid.
Output result as -
/--------------------------------------------\
| cid | name | mobile | date | balance |
|--------------------------------------------|
| 1 | ABC | 12345 | 2013-09-20 | 300 |
|--------------------------------------------|
| 2 | XYZ | 98475 | 2013-09-21 | 600 |
\--------------------------------------------/
回答1:
You need to use two sub-queries like this:
SELECT a.cid, a.name, a.mobile, b.date, b.balance
FROM account a
JOIN
(
SELECT b1.* FROM balance b1
JOIN
(
SELECT cid, MAX(Date) As maxDate
FROM balance
GROUP BY cid
) b2
ON b1.cid = b2.cid
AND b1.date = b2.maxDate
) b
ON a.cid = b.cid;
Output:
CID | NAME | MOBILE | DATE | BALANCE |
---|---|---|---|---|
1 | ABC | 12345 | September, 20 2013 00:00:00+0000 | 300 |
2 | XYZ | 98475 | September, 21 2013 00:00:00+0000 | 600 |
See this SQLFiddle
回答2:
SELECT a.cid, a.name, a.mobile, MAX(b.date), b.balance
FROM account AS a
INNER JOIN balance AS b
WHERE a.cid=b.cid
GROUP BY cid;
Sorry I din't notice the balance column in 3rd table.
SELECT a.cid, a.name, a.mobile, b.date, b.balance
FROM account AS a
INNER JOIN (
SELECT c.date, c.cid, c.balance FROM balance AS c
INNER JOIN (
SELECT cid AS cid2, MAX(date) AS date2
FROM balance
GROUP BY cid2) AS d
ON c.cid=d.cid2
AND c.date=d.date2
) AS b
ON a.cid=b.cid
GROUP BY cid;--
回答3:
This following statement should get you the required result :
SELECT cid, name, mobile, MAX(date), blance
FROM account
LEFT JOIN balance
ON account.cid = balance.cid
GROUP BY balance.cid
来源:https://stackoverflow.com/questions/18928992/mysql-join-two-table-with-the-maximum-value-on-another-field