如何将LEFT JOIN限制为一个结果并从结果集中返回最低值?

时间:2012-07-29 00:08:23

标签: mysql

假设我有这样的查询:

SELECT t1.name, t2.likes
FROM table_1 t1
LEFT JOIN table_2 t2 ON t1.name = t2.name

如何修改左连接以使其执行以下操作:

SELECT likes FROM table_2 WHERE name = [name from table 1] ORDER BY likes ASC

我尝试编写子查询,但它没有用,因为(我假设)你不能在子查询中使用子查询外部的变量(例如名称)(名称不是常量,作为结果集从查询中将不止一个)。

这可能吗?

编辑:表格将是这样的:

TABLE_1:

+------+--------+
| id   |  name  |
+------+--------+
|  0   |  cat   |
|  1   |  dog   |
+------+--------+

表2:

+------+--------+---------+
| id   |  name  |  likes  |
+------+--------+---------+
|  0   |  cat   |   23    |
|  1   |  cat   |   2     |
|  2   |  cat   |   53    |
|  3   |  dog   |   25    |
|  4   |  dog   |   12    |
+------+--------+---------+

所以,我想要的是:

+--------+---------+
|  name  |  likes  |
+--------+---------+
|  cat   |   2     |
|  dog   |   12    |
+--------+---------+

2 个答案:

答案 0 :(得分:4)

SELECT 
    t1.name, t2.likes
FROM table_1 t1
LEFT JOIN (
    SELECT
    name,
    MIN(likes) as likes 
    FROM table_2 
    GROUP BY name
) as t2 ON t1.name = t2.name

您也可以使用子查询来完成,但我认为这会更慢:

SELECT 
    t1.name,
    (SELECT MIN(likes) FROM table_2 WHERE table_2.name = t1.name)
FROM table_1 t1

答案 1 :(得分:2)

每个名称

最低likes

SELECT   name, MIN(likes) AS likes
FROM     table_2
GROUP BY name

如果您需要有关name的更多信息,请加入table_1表,将上述查询合并到子选择中:

SELECT a.name, b.likes
FROM   table_1 a
LEFT JOIN
(
    SELECT   name, MIN(likes) AS likes
    FROM     table_2
    GROUP BY name
) b ON a.name = b.name