【问题标题】:SQLite3, Select From Two Tables One with Priority?SQLite3,从两个表中选择一个优先级?
【发布时间】:2012-07-27 13:19:14
【问题描述】:

所以我有两个 sqlite3 表

表 1

ID Color Value
1 red    5
2 green  3
3 yellow 5
4 blue   1
5 white  4

表 2

ID Color Value
2 green  6
3 yellow 2
5 white  3

如果可能的话,我想用一个选择做的是:

ID Color Value
1 red    5
2 green  6
3 yellow 2
4 blue   1
5 white  3

所以使用表 1 中的记录,除非它存在于表 2 中。如果记录存在于表 2 中,则使用它。

我查看了工会,但没有运气。我添加了第四列,其中包含 1 或 0,1 是表 2 数据,并尝试使用 order by/limit 1 为表 2 设置优先级,但这也不起作用。

我希望有一个可以自动执行的选择,而我不必为选择提供 where 子句和要排除的项目,这样我就必须连接一个字符串查询。

这可能吗?

【问题讨论】:

    标签: sqlite select join union


    【解决方案1】:
    select t1.ID, case when t2.Color is not null 
                       then t2.Color
                       else t1.Color
                  end as Color,
                  case when t2.Value is not null 
                       then t2.Value
                       else t1.Value
                  end as Value
    from table1 t1
    left outer join table2 t2 on t1.id = t2.id
    

    编辑

    一个更短的版本(感谢 Doug)是:

    select t1.ID, 
           coalesce(t2.Color, t1.Color) as Color, 
           coalesce(t2.Value, t1.Value) as Value
    from table1 t1
    left outer join table2 t2 on t1.id = t2.id
    

    【讨论】:

    • 您的解决方案看起来不错,但您可以将 case 语句替换为 coalesce(t2.Color, t1.Color) as Color, coalesce(t2.Value, t1.Value) as Value
    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 2021-04-08
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多