SQLite从tbl2(或tlb1,如果不存在)中选择值

时间:2018-11-23 10:40:46

标签: sqlite

我有两个表tbl1tbl2,分别具有行idprice,其中tbl1包含许多记录,而tbl2仅包含少

我想从tbl1中选择所有条目,但要用price中的数据替换tbl2,如果它存在于tbl2

到目前为止,我得到的查询不起作用:

SELECT p.id,
       CASE p.id WHEN p.id IN (
                SELECT id
                  FROM tbl2
            )
       THEN o.price
       ELSE p.price END AS 'price'
  FROM tbl1 p
       LEFT JOIN tbl2 o ON p.id = o.id

示例tbl1

id  price
1   1.23
2   4.56
3   7.89

示例tbl2

id  price
2   99.99

期望的查询结果

id  price
1   1.23
2   99.99    <--- entry from tbl2
3   7.89   

1 个答案:

答案 0 :(得分:2)

只需使用<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:assembly="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:shared="urn:mlog-sharedclasses-ns" xmlns:visu="urn:mlog-visucommon-ns" Width="2000" Height="1000" Background="White" TextBlock.FontFamily="{StaticResource OpenSans}" assembly:Name="rootElement" mc:Ignorable="d"> <Grid.Resources> <BoolToBrushConverter xmlns="clr-namespace:ControlPanel.SharedClasses.Converters;assembly=MCC.ControlPanel.SharedClasses" FalseValue="#FF00FFFF" TrueValue="#FF0000FF" assembly:Key="ID_880cf_BorderBrush_Converter" /> </Grid.Resources> <visu:TagRootCanvas> <Button Content="Button" Width="412" Height="231" Canvas.Left="33" Canvas.Top="71" assembly:Name="ID_880cf"> <i:Interaction.Behaviors> <visu:TagBindingBehavior xmlns:av="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="urn:mlog-visucommon-ns" Converter="{av:StaticResource ID_880cf_BorderBrush_Converter}" Debug="False" Mode="OneWay" Property="{shared:Static Member=av:Border.BorderBrushProperty}" TagDataType="Bool" TagName="aaa" UpdateSourceTrigger="Default" UseConvertedNullAsFallback="False" /> </i:Interaction.Behaviors> </Button> </visu:TagRootCanvas> </Grid> 选择正确的价格:

COALESCE

enter image description here

Demo

这里的逻辑是,我们使用第二个表中的SELECT p.id, COALESCE(o.price, p.price) price FROM tbl1 p LEFT JOIN tbl2 o ON p.id = o.id; ,假设它存在于给定的price中。如果不存在,那么我们退回到使用第一个表中的id