如何连接表以选择连接表中的最大行?

时间:2018-01-19 21:22:14

标签: mysql join left-join greatest-n-per-group outer-join

我有两个表,我想在一个属性上加入它们,但是我不想在第二个表中选择所有匹配的行,而是只选择具有最高编号(最新日期等)的条目。某一栏。如何在SQL中表达此结果?

这是一个简化的例子来澄清我的问题。

Table `colors`
| color |
+-------+
| red   |
| green |
| blue  |


Table `inventory`
| color | value | shape    |
+-------+-------+----------|
| red   | 1     | square   |
| red   | 2     | circle   |
| green | 7     | triangle |


Desired output:
| color | value | shape    |
+-------+-------+----------|
| red   | 2     | circle   |
| green | 7     | triangle |
| blue  | NULL  | NULL     |

我的桌子相当大,所以理想情况下解决方案效率会相当高。 (不需要微调,只是试图避免可能变得巨大的双连接。)

2 个答案:

答案 0 :(得分:2)

select c.color, i2.value, i2.shape
from colors c
left join 
(
   select color, max(value) as value
   from inventory 
   group by color
) i on c.color = i.color
left join inventory i2 on i2.color = i.color
                      and i2.value = i.value

答案 1 :(得分:2)

http://sqlfiddle.com/#!9/0b75c/6

SELECT c.*, i.value, i.shape
FROM colors c
LEFT JOIN inventory i
ON c.color = i.color
LEFT JOIN inventory i_
ON i.color = i_.color
  AND i.value<i_.value
WHERE  i_.color IS NULL

http://sqlfiddle.com/#!9/0b75c/8

SELECT i.value, i.shape
FROM inventory i
LEFT JOIN inventory i_
ON i.color = i_.color
  AND i.value<i_.value
WHERE  i_.color IS NULL