简体   繁体   中英

join in sql or ms-access?

There is a table like this in the format of SQL or ms-access.

Sample

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          

I need to replace "~" in example fields(A) with the value of name field that has the same ID2 as A and class = "main". How do I make a join syntax?

Result

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          

I think your table configuration is not correct.

The fact that you are using a ID field whose valor is repeated on the table points to a somewhat bad database design.

I think you'd probably get better results splitting your data between two tables, one with the examples and one with the "main" classes. Then you'll be able to join both tables through a simple join using ID2 field.

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 

Although the data is structured terribly (for whatever reason), to answer your question, you can do it like this:

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")

This relies on the assumption that there is only one record with class=main for each unique value of ID2 (otherwise you will get repeats of rows).

Without the requirement of using a JOIN, an alternative is this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM