1

我在 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

4 回答 4

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
于 2013-03-06T10:24:04.157 回答
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
于 2013-03-06T10:24:40.743 回答
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;

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

于 2013-03-06T10:26:55.410 回答
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
于 2013-03-06T10:32:51.497 回答