MySQL 条件左连接默认值

标签 mysql left-join conditional-statements

有没有办法创建一个条件左连接,如果未找到匹配项,它将在默认值上左连接

我有一个client 表和一个preference 表。 preference 表中的记录 0 是我的全局默认首选项。在某些情况下,客户端可能会覆盖全局引用,在这种情况下,客户端将在首选项表中拥有自己的记录。

因此,我希望在 client.ClientID =preference.ClientID 上对首选项表进行左连接,但是如果没有匹配项,那么我想要改为左加入 preference.ClientID = 0

最佳答案

SqlFiddle Demo

select * from client, preference
where preference.clientID in (select MAX(preference.ClientID)
                              from preference 
                              where preference.ClientID = client.ClientID OR preference.ClientID = 0)

select client.name, MAX(preference.ClientID)
from client
left join preference on preference.ClientID = client.ClientID OR preference.ClientID = 0
group by client.name

关于MySQL 条件左连接默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687076/

相关文章:

mysql - 在连接 2 个表的情况下在两个表上创建索引的好处

mysql - 无法捆绑 exec rake :db:rollback due to errno: 150 - Foreign key constraint is incorrectly formed

php - 如何使用 php 打印 json 响应

SQL Server 使用 'Or' 运算符进行左连接

mysql - 正确的 MySQL Left Join Query 会使小型数据库负担过重,尽管行已被索引

c# - LINQ 左连接可空列给出空引用异常

c++ - 重载类型转换为 bool 和效率

GCC 中的 C 条件运算符

R:有条件替换数据框中多列中的值

mysql - 在 MySQL 中格式化日期以返回 MonthName,Year