【问题标题】:join in sql or ms-access?加入sql还是ms-access?
【发布时间】:2012-09-17 13:07:58
【问题描述】:

有一个这样的表,格式为SQL或ms-access。

样本

ID  ID2 name    class   example
1   10  John    main    
2   10          
3   10          
4   10                  ~ is look at me.
5   20  Candice main    
6   20          
7   20                  ~ is in Japan.
8   20                  ~ is reading a book.
9   20          

我需要将示例字段(A) 中的“~”替换为与 A 具有相同 ID2 且 class=“main”的名称字段的值。如何进行连接语法?

结果

ID  ID2 name    class   example
1   10  John    main    
2   10          
3   10          
4   10                  John is look at me.
5   20  Candice main    
6   20          
7   20                  Candice is in Japan.
8   20                  Candice is reading a book.
9   20          

【问题讨论】:

  • ...然后去阅读规范化

标签: sql ms-access join


【解决方案1】:

我认为你的表配置不正确。

您使用的 ID 字段的值在表上重复,这表明数据库设计有些糟糕。

我认为在两张表中拆分数据可能会得到更好的结果,一张带有示例,一张带有“主”类。然后,您将能够通过使用 ID2 字段的简单连接来连接两个表。

【讨论】:

  • 虽然有效,但这并不能回答问题.... OP 会问:这个表是 3NF 还是更高版本?
【解决方案2】:
select m.[name] & replace(b.example, "~", "") as combined
from sample as m
inner join sample as b on m.id2 = b.id2
where m.[class] = "main"
and b.example not null 

【讨论】:

    【解决方案3】:

    尽管数据结构非常糟糕(无论出于何种原因),但要回答您的问题,您可以这样做:

    SELECT 
       T1.[ID],
       T1.[ID2],
       T1.[name],
       T1.[class],
       iif(not isnull(T1.[Example]) and not isnull(T2.[Name]), Replace(T1.[Example], "~", T2.[Name]), null) As [Example]
    FROM
       Data T1
    LEFT JOIN Data T2 ON (T1.[ID2] = T2.[ID2] AND T2.[Class]="main")
    

    这依赖于这样一个假设:对于 ID2 的每个唯一值,只有一个 class=main 的记录(否则您会得到重复的行)。

    不需要使用 JOIN,另一种方法是:

    SELECT 
       [ID],
       [ID2],
       [name],
       [class],
       (iif(not isnull([example]), Replace([example], "~", nz((select top 1 [name] from Data T2 where T2.ID2 = T1.ID2 and T2.[class]="main" order by T2.[ID2]),"")),null)) as [ExampleNew]
    FROM Data T1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多