mysql - 使用另一个字段的值作为左连接的默认值

标签 mysql sql left-join default-value

我有以下 3 个表:

users
| id | name  | address  |
|----+-------+----------+
| 1  | user1 | address1 |
| 2  | user2 | address2 |

locations
| id | user_id | name      |
|----+---------+-----------+
| 1  | 1       | location1 |
| 2  | 1       | location2 |
| 3  | 2       | location3 |

orders
| id | user_id | from_id | to_id |
|----+---------+---------+-------+
| 1  | 1       | 1       | 2     |
| 2  | 1       | 1       | 0     |

from_id 或 to_id 可以为 0,这意味着在本例中使用了用户的地址。

在这些表上执行“简单”连接:

SELECT u.name uname, fl.location flocation, tl.location tlocation
FROM   users u, orders o, locations fl, locations tl
WHERE  u.id = o.user_id
  AND  o.from_id = fl.id
  AND  o.to_id = tl.id

不显示带0的记录:

user1 | location1 | location2

我想看到的是以下数据:

user1 | location1 | location2
user1 | location1 | address1

使用mysql,有没有办法扩展连接来显示这样的结果?

最佳答案

下面的 SQL 应该可以做到这一点:

SELECT u.name uname, IF(fl.id, fl.location, u.address) AS flocation, IF(tl.id, tl.location, u.address) AS tlocation
FROM users u
    INNER JOIN orders o ON u.id = o.user_id
    LEFT JOIN locations fl ON o.from_id = fl.id
    LEFT JOIN locations tl ON o.to_id = tl.id;

如果我可以提出建议,我建议您不要使用 WHERE 子句作为连接表的方式。

关于mysql - 使用另一个字段的值作为左连接的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670888/

相关文章:

sql - 在Oracle中,如何在聚合所有行时选择特定行

sql - 无法通过 IP 和命名实例远程连接到 SQL 2012

r - 使用 stringdist_join 连接多列

mysql - 标准化 : is it worth it for small words (more queries needed)?

php - 在 sql 查询中使用 SESSION 变量时尝试获取非对象的属性

mysql - 将 case 语句的结果连接到列的值

mysql - REGEX sql 查询

sql - 为自定义产品类型定义通用数据模型

mysql - 单个表上的 SQL 左连接

sql - 用日期表填补日期空白