SQL SELECT仅包含两个不同表中列的MAX值的行

时间:2016-08-05 07:03:37

标签: php mysql sql database

我的两个表设置如下:

表1

+------+---------+--------------------------------------+
| id   | tail    | content                              |
+------+---------+--------------------------------------+
| 1    | abc     | ...                                  |
| 2    | def     | ...                                  |
| 3    | ghi     | ...                                  |
| 4    | def     | ...                                  |
| 5    | jkl     | ...                                  |
+------+-------+----------------------------------------+

表2

+------+--------+---------------------------------------+
| id   | tailID | value   |  others                     |
+------+--------+---------------------------------------+
| 1    | 2      | 412     |                             |
| 2    | 3      | 215     |                             |
| 1    | 2      | 571     |                             |
| 1    | 4      | 123     |                             |
+------+--------+---------------------------------------+

我喜欢将这两个表中的所有列连接到匹配的tail = tailID,但不是具有相同尾部的重复行。

对于重复的TAIL,只需要获得相同尾部的最大值的单行。

我目前正在使用

SELECT table1.tail, table2.other_column 
FROM table1 
INNER JOIN table2 
on table1.id = table2.tailID 
WHERE table1.some_coloum = "a sepecific string" 
ORDER BY table2.value

但它会返回许多相同尾部的副本。

我只需要为表格2的高值VALUE设置重复TAIL的单行。

3 个答案:

答案 0 :(得分:2)

DISTINCT with CROSS APPLY:

SELECT DISTINCT t1.tail,
                t2.other_column,
                t3.[value]
FROM table1 t1
CROSS APPLY (
    SELECT  tailid,
            MAX([value]) as [value]
    FROM table2
    WHERE tailid = t1.id
    GROUP BY tailid
    ) as t3
INNER JOIN table2 t2
    ON t2.tailid = t3.tailid AND t3.[value] = t2.[value]
WHERE t1.some_coloum = "a sepecific string" 

答案 1 :(得分:1)

第一组table2然后加入

SELECT table1.tail, table2.other_column 
FROM table1 
INNER JOIN (
   SELECT tailID, max(value) as value
   FROM table2
   GROUP BY tailID
) t2g ON t2g.tailID = table1.ID
INNER JOIN table2 
on t2g.tailID = table2.tailID AND  t2g.value = table2.value
WHERE table1.some_coloum = "a sepecific string" 
ORDER BY table2.value

如果table1中有2行或更多行具有相同的table2max(value),则查询仍可能会为tailID行返回多行。

答案 2 :(得分:0)

仅选择列value

的MAX值的行
SELECT table1.tail, MAX(table2.value)
FROM
  table1
  INNER JOIN table2 ON table1.id = table2.tailID
  WHERE table1.content = "test"

http://sqlfiddle.com/#!9/b70d29/3/0