给定下表
orders
+----+---------+---------+
| id | user_id | details |
+----+---------+---------+
| 1 | 2 | blue |
+----+---------+---------+
| 2 | 1 | red |
+----+---------+---------+
| 3 | 2 | yellow |
+----+---------+---------+
| 4 | 2 | cyan |
+----+---------+---------+
users
+---------+---------+---------+
| user_id | ph | name |
+---------+---------+---------+
| 1 | 123 | fred |
+---------+---------+---------+
| 2 | 456 | Stan |
+---------+---------+---------+
| 3 | 189 | Levi |
+---------+---------+---------+
我知道如何使用 distinct 在第一个表中只选择每个用户的一次出现
SELECT DISTINCT user_id FROM orders
我怎样才能只从用户那里提取电话号码?
我可能会循环并挑选出每个数字,例如...
SELECT ph from users WHERE user_id = user_id
不禁想到我可能会使用一个单行查询。
结果是
123
456
最佳答案
从 Orders 表中选择 Distinctively 可能是一项繁重的操作。取决于该表将变得有多大。
也许这个会更快:
Select u.ph
from users u
where exists (select id from orders where user_id = u.user_id);
关于mysql - 从两个表中选择不同的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11031956/