我有两个表用户和* activation_details *
用户表包含这些数据。 uid是主键。
uid | user_name
______________________
1 | John Smith
2 | Mary Smith
3 | Nancy Smith
4 | Agent Smith
activation_details有这些数据
aid | is_activated | user_id
______________________________________
1 | 0 | 0
2 | 1 | 4
3 | 1 | 1
4 | 1 | 777
请注意,用户ID 777不在用户表中。
我需要这种格式的结果
aid | is_activated | user_name
______________________________________________
1 | 0 | 0
2 | 1 | Agent Smith
3 | 1 | John Smith
4 | 1 | 777
如果用户表中存在用户ID,则必须显示用户名,否则必须显示user_id本身。
我试过这样的事情
SELECT aid, is_activated, user_id, users.user_name from activation_details, users WHERE users.uid = user_id
它提供此输出,这是无用的。
aid | is_activated | user_name | user_id
________________________________________________________
2 | 1 | Agent Smith | 4
3 | 1 | John Smith | 1
无论如何只使用mysql获取此输出,我可以用PHP中的多个查询来完成,但这不是我想要的。
aid | is_activated | user_name
______________________________________
1 | 0 | 0
2 | 1 | Agent Smith
3 | 1 | John Smith
4 | 1 | 777
答案 0 :(得分:3)
您希望将外部联接与coalesce()
函数(返回所选列中的第一个非null值)结合使用,如下所示:
SELECT
a.aid,
a.is_activated,
a.user_id,
coalesce(b.user_name, a.user_id, 0) as User
from
activation_details a
left outer join users b
on a.user_id=b.uid
修改:我为coalesce()
函数添加了一项检查,如果0
和user_name
字段均为空值,则会为用户返回user_id
。
在mysql中完成测试:
mysql> select * from first
-> ;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
+------+-------+
3 rows in set (0.00 sec)
mysql> select coalesce('a', id) from first
-> ;
+-------------------+
| coalesce('a', id) |
+-------------------+
| a |
| a |
| a |
+-------------------+
3 rows in set (0.00 sec)
mysql> select coalesce('a', 1) from first;
+------------------+
| coalesce('a', 1) |
+------------------+
| a |
| a |
| a |
+------------------+
3 rows in set (0.00 sec)
mysql> select coalesce(null, 1) from first;
+-------------------+
| coalesce(null, 1) |
+-------------------+
| 1 |
| 1 |
| 1 |
+-------------------+
3 rows in set (0.00 sec)
答案 1 :(得分:2)
SELECT t3.aid,t3.is_activated,
IF (t2.user_name IS NOT null, t2.user_name, t3.user_id)
FROM activation_details AS t3
LEFT JOIN users AS t2 ON t3.user_id = t2.uid;
我认为这个查询会给出结果