如何组合来自两个表的数据

本文关键字:两个 数据 何组合 组合 | 更新日期: 2023-09-27 18:16:39

我有两个表

Table1: TheaterDetail

t_id    t_Address    t_Name   c_id
1       ahmedabad    Cinemax1   1
2       Baroda       Cinemax2   2
3       Jamnagar     Cinemax3   3
4       Rajkot       Cinemax4   4
5       Surat        Cinemax5   5
6       Junagadh     Cinemax2   2

表二:CityDetails

c_id    City_name
1       Ahm
2       Bar
3       Jam
4       Raj
5       Sur

我想要像那样放出去,可能吗?我是新的sql,所以我发现它很难。我希望列名显示在输出(t_address,t_name)

Ahm 
t_address   t_name
ahmedabad   Cinemax1
Bar 
t_address   t_name
Baorda  Cinemax2
Junagadh Cinemax2
Jam 
t_address   t_name
Jamnagar    Cinemax3
Raj 
t_address   t_name
Rajkot  Cinemax4
Sur 
t_address   t_name
Surat   Cinemax5

我做了两个像这样的查询

 select distinct city_name from CityDetail A inner join TheaterDetail B
    on A.c_id = B.c_id where a.c_id= 2
   city_name
   Bar

和其他类似的查询

select t_Address,t_Name from TheaterDetail C inner JOin CityDetail D
on C.c_id = D.c_id where D.c_id= 2
t_Address   t_Name
Baroda      Cinemax2
Junagadh    Cinemax2

如果我在city_id=2上设置条件,我的输出将是这样的

Bar 
t_address   t_name
Baorda      Cinemax2
Junagadh    Cinemax2

如何组合来自两个表的数据

这将是您想要的查询

    drop table Tbl1
    Create table Tbl1
    (
        iSrno int identity(1,1) not null,
        c_id numeric(18,2),
        city_name nvarchar(500) 
        ,t_name nvarchar(500)
    )
    Insert into Tbl1 
    select c_id,city_name as city_name, '' as t_name from CityDetails
    Union
    select c_id, 't_address','t_name'  from CityDetails
    Insert into Tbl1 
    select b.c_id,a.t_address,a.t_name  from TheaterDetail as a 
    Inner join CityDetails b on a.c_id= b.c_id
select * from Tbl1 Order by c_id asc , iSrno asc