使用与此问题相关的问题Get Last Row of Different id then display data that is greater than zero
我想加入另一张表
这是我的table2
+----+--------+
| id | name |
+----+--------+
| 1 | Taylor |
| 2 | Zac |
| 3 | Scott |
| 4 | Emma |
+----+--------+
如果我使用此代码......
SELECT DISTINCT t1.id, t1.amount, t2.name FROM table1 t1, table2 t2 WHERE t1.amount = (SELECT MIN(t1.amount) FROM table1 WHERE id= t1.id) AND t1.[t1.amount]>0 AND t1.[id]=t2.[id];
......然后这些结果显示......
+----+--------+-------+
| id | amount | name |
+----+--------+-------+
| 2 | 100 | Zac |
+----+--------+-------+
仅显示1个数据
我想要的是表格中的数据
+----+--------+-------+
| id | amount | name |
+----+--------+-------+
| 2 | 100 | Zac |
| 4 | 200 | Emma |
+----+--------+-------+
答案 0 :(得分:0)
相信你正在寻找第一张表的子查询,请尝试以下方法:
SELECT DISTINCT t1.id, t1.amount, t2.name
FROM (SELECT DISTINCT id, amount FROM table t
WHERE amount = (SELECT MIN(amount) FROM table WHERE id= t.id)
and amount>0) t1, table2 t2
WHERE t1.[id]=t2.[id];
不确定为什么您当前的查询不起作用,但希望这有帮助!
答案 1 :(得分:0)
SELECT DISTINCT t.id,t2.name,t.amount
FROM table t
INNER JOIN table2 t2 ON t.id=t2.id
WHERE amount = (SELECT MIN(amount) FROM table WHERE id= t.id)
and amount>0;
答案 2 :(得分:0)
请尝试以下方法......
SELECT table2.id AS id,
minAmount AS amount,
name
FROM ( SELECT id,
MIN( amount ) AS minAmount
FROM table1
GROUP BY id
HAVING MIN( amount ) > 0
) AS table1Refiner
INNER JOIN table2 ON table1Refiner.id = table2.id;
此声明的工作原理是根据您的第一个问题获取结果,并根据table2
的共享值将其加入id
,有效地将相应的name
附加到每个id
}和amount
。然后选择并输出字段。
如果您有任何问题或意见,请随时发表评论。