主資料表(pro)
關聯3個資料表(a,b,c)
3個資料表各有數筆資料(下面以兩筆做測試)
3個資料表資料彼此無規則
因目前常用的left join 結果不容易閱讀
或是搭配PHP希望呈現以下圖表格
測試資料
CREATE TABLE a(
noa nvarchar(20),
pro nvarchar(20)
);
insert into a
select 'a-1','D2023-01-001'
insert into a
select 'a-2','D2023-01-001'
CREATE TABLE b(
noa nvarchar(20),
pro nvarchar(20)
);
insert into b
select 'b-1','D2023-01-001'
insert into b
select 'b-2','D2023-01-001'
CREATE TABLE c(
noa nvarchar(20),
pro nvarchar(20)
);
insert into c
select 'c-1','D2023-01-001'
insert into c
select 'c-2','D2023-01-001'
CREATE TABLE pro(
noa nvarchar(20)
);
insert into pro
select 'D2023-01-001'
--=============== Table A ===============
CREATE TABLE #a (
noa NVARCHAR(20),
pro NVARCHAR(20)
);
INSERT INTO #a
SELECT 'a-1','D2023-01-001'
INSERT INTO #a
SELECT 'a-2','D2023-01-001'
--=============== Table A ===============
--=============== Table B ===============
CREATE TABLE #b(
noa NVARCHAR(20),
pro NVARCHAR(20)
);
INSERT INTO #b
SELECT 'b-1','D2023-01-001'
INSERT INTO #b
SELECT 'b-2','D2023-01-001'
--=============== Table B ===============
--=============== Table C ===============
CREATE TABLE #c(
noa NVARCHAR(20),
pro NVARCHAR(20)
);
INSERT INTO #c
SELECT 'c-1','D2023-01-001'
INSERT INTO #c
SELECT 'c-2','D2023-01-001'
--=============== Table C ===============
--=============== Table pro ===============
CREATE TABLE #pro(
noa NVARCHAR(20)
);
INSERT INTO #pro
SELECT 'D2023-01-001'
--=============== Table pro ===============
--=============== Table Join ===============
SELECT
#pro.noa
,#a.noa
,#b.noa
,#c.noa
FROM #pro
INNER JOIN #a
ON #pro.noa = #a.pro
INNER JOIN #b
ON SUBSTRING(#a.noa,LEN(#a.noa),1) = SUBSTRING(#b.noa,LEN(#b.noa),1)
INNER JOIN #c
ON SUBSTRING(#a.noa,LEN(#a.noa),1) = SUBSTRING(#c.noa,LEN(#c.noa),1)
--=============== Table Join ===============
DROP TABLE #pro,#a,#b,#c
PS:#pro.noa 這個值,用PHP語法判斷,重複的話,顯示空白
查三次 然後用php自己拚array也是可以的吧