1

假设我有这样的查询:

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

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

那有可能吗?

编辑:表格将是这样的:

表格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    |
+--------+---------+
4

2 回答 2

5
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
于 2012-07-29T00:14:12.493 回答
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
于 2012-07-29T00:17:30.533 回答