如何加入 tables 以选择加入的 table 中的最大行?
How do I join tables to choose the maximum row in the joined table?
我有两个 table,我想在一个属性上加入它们,而不是在第二个 table 中获取所有匹配的行,我只想选择带有特定列中的最高数字(最新日期等)。我如何在 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 |
我的 table 相当大,因此理想情况下,解决方案会相当有效。 (不需要微调,只是试图避免可能变得巨大的双重连接。)
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
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
我有两个 table,我想在一个属性上加入它们,而不是在第二个 table 中获取所有匹配的行,我只想选择带有特定列中的最高数字(最新日期等)。我如何在 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 |
我的 table 相当大,因此理想情况下,解决方案会相当有效。 (不需要微调,只是试图避免可能变得巨大的双重连接。)
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
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