DECLARE @t1 TABLE (T1_key int, T1_Data char(1), T1_ValidUntil datetime)
DECLARE @t2 TABLE (T2_key int, T2_Data char(1), T2_ValidUntil datetime)
INSERT @t1 VALUES (1, 'A', '2000-01-01')
INSERT @t1 VALUES (1, 'B', '2000-06-30')
INSERT @t1 VALUES (2, 'C', '2005-05-31')
INSERT @t1 VALUES (3, 'D', '2004-12-31')
INSERT @t1 VALUES (3, 'E', '2007-04-30')
INSERT @t1 VALUES (3, 'F', '2008-01-31')
INSERT @t2 VALUES (1, 'R', '2002-03-31')
INSERT @t2 VALUES (2, 'S', '2001-06-30')
INSERT @t2 VALUES (2, 'T', '2003-02-28')
INSERT @t2 VALUES (2, 'U', '2005-05-31')
INSERT @t2 VALUES (3, 'V', '2006-09-30')
INSERT @t2 VALUES (3, 'W', '2007-06-30')
SELECT
T1.*, T2x.*
FROM
@t1 T1
CROSS APPLY
(SELECT TOP 1*
FROM @t2
WHERE T1_key = T2_key AND T2_ValidUntil >= T1_ValidUntil
ORDER BY T2_ValidUntil
) T2x
UNION
SELECT
T1x.*, T2.*
FROM
@t2 T2
CROSS APPLY
(SELECT TOP 1*
FROM @t1
WHERE T1_key = T2_key AND T1_ValidUntil >= T2_ValidUntil
ORDER BY T1_ValidUntil
) T1x
All INNER JOINs and UNIONs maybe
PROPOSED QUERY
select id t1_id,NULL t2_id,NULL t3_id,NULL t4_id from t1
union select t1.id,t2.id,NULL,NULL from t1
inner join t2 using (id)
union select t1.id,t2.id,t3.id,NULL from t1
inner join t2 using (id)
inner join t3 using (id)
union select t1.id,t2.id,t3.id,t4.id from t1
inner join t2 using (id)
inner join t3 using (id)
inner join t4 using (id)
;
SAMPLE DATA
use test
drop table if exists t1;
drop table if exists t2;
drop table if exists t3;
drop table if exists t4;
create table t1
(
id int not null,
name varchar(20),
primary key (id)
);
insert into t1 values (1,'name1');
create table t2 like t1; insert into t2 values (1,'name2');
create table t3 like t1; insert into t3 values (1,'name3');
create table t4 like t1; insert into t4 values (1,'name4');
PROPOSED QUERY EXECUTED
mysql> select id t1_id,NULL t2_id,NULL t3_id,NULL t4_id from t1
-> union select t1.id,t2.id,NULL,NULL from t1
-> inner join t2 using (id)
-> union select t1.id,t2.id,t3.id,NULL from t1
-> inner join t2 using (id)
-> inner join t3 using (id)
-> union select t1.id,t2.id,t3.id,t4.id from t1
-> inner join t2 using (id)
-> inner join t3 using (id)
-> inner join t4 using (id)
-> ;
+-------+-------+-------+-------+
| t1_id | t2_id | t3_id | t4_id |
+-------+-------+-------+-------+
| 1 | NULL | NULL | NULL |
| 1 | 1 | NULL | NULL |
| 1 | 1 | 1 | NULL |
| 1 | 1 | 1 | 1 |
+-------+-------+-------+-------+
4 rows in set (0.00 sec)
mysql>
All the columns have id as a common name. If you want, I can adjust my answer with the id names
Best Answer
You can get the result by using a
LEFT JOIN
between themaincolor
and thesubcolor
.The key is placing the filter of
status=1
on theJOIN
condition. Your code will be:See SQL Fiddle with Demo.
The
LEFT JOIN
will return all rows from themaincolor
table and any matching rows in thesubcolor
table. Since you what to apply aWHERE
to the data in thesubcolor
table, then you will want to move that filter to theJOIN
condition to get the result.