选择具有2种排序类型的记录

时间:2013-03-06 10:20:12

标签: mysql sql sorting subquery

mySQL中有2个表,包含以下数据:

表1:

id     |   title
-------+-----------
1      |  Test 1
2      |  Test 2
3      |  Test 3
4      |  Test 4

表2:

id     |  table1_id   |   price
-------+--------------+----------
1      | 1            | 15000
2      | 1            | 2000
3      | 1            | 32600
4      | 2            | 1000
5      | 3            | 4000
6      | 4            | 5500
7      | 2            | 3000

现在我希望从Table 1id排序选择所有记录,然后从price中选择最大的Table 2,所以我写了这个查询:

SELECT a.*, b.price
FROM table1 AS a, table2 AS b
WHERE a.id = b.table1_id
GROUP BY a.id
ORDER BY a.id ASC, b.price DESC

但结果是Table 2中的第一个价格。

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT DISTINCT a.*, MAX(b.price)
FROM table1 AS a, table2 AS b
WHERE a.id = b.table1_id
GROUP BY a.id
ORDER BY a.id ASC

答案 1 :(得分:1)

你可以用group by或subselect来做(更好的解决方案,将选择没有价格的table1记录)

SELECT
    a.*,
    b.price
FROM table1 AS a
LEFT OUTER JOIN
(
    SELECT  
        table1_id,
        MAX(price) AS price
    FROM table2
    GROUP BY table1_id
) AS b
    ON b.table1_id = a.id
ORDER BY a.id ASC, b.price DESC

答案 2 :(得分:0)

你需要的是第二张桌子上的分组最大值。

SELECT a.*, b.price
FROM table1 a
JOIN table2 b ON a.id = b.table1_id
LEFT JOIN table2 b2 ON b.table1_id=b2.table1_id AND b.price<b2.price
WHERE b2.id IS NULL
ORDER BY a.id ASC;

此查询的优点是您可以从第二个表中选择所有数据,而不仅仅是最高价格。

答案 3 :(得分:0)

尝试

SELECT t1 . * , MAX( t2.price ) 
FROM table1 t1, table2 t2
WHERE t1.id = t2.table1_id
GROUP BY t1.id
ORDER BY t1.id ASC