无论空数据如何,都要连接两个数据表

时间:2013-10-17 03:24:41

标签: mysql join

所以我有两张桌子,看起来像这样;

table_a                            table_b
reg     |rm     |date              reg     |rm     |date
========+=======+==========        ========+=======+==========
1       |1      |2013-01-01        2       |2      |2013-01-01
1       |1      |2013-01-02        2       |2      |2013-01-05
3       |2      |2013-01-08        3       |2      |2013-01-08

- 我知道它看起来像两个不同的表,它们具有相同的数据但实际上它有不同的列,我只是没有包含与此问题无关的任何其他列

这是我在rm=2搜索时想要实现的目标;

result
reg     |date
========+==========
3       |2013-01-08
2       |2013-01-01

当我尝试使用join时,reg 2中的table_b没有出现,当我尝试union all时,它说reg不能为空,因为我使用min(date)来获得最早的约会。 (当我删除min功能时它没有错误,但它会显示每个日期 - 我只需要最早的日期和order by date desc

这是我要实现的目标;

SELECT b.reg, min(b.date) as ddate
FROM table_a a 
join table_b b on (o.reg=a.reg) 
where b.rm = '2'
order by ddate desc

和这个

select reg,min(date) as ddate from table_a where rm = '2'                  
union all
select reg,min(date) as ddate from table_b where rm = '2'
order by ddate desc

2 个答案:

答案 0 :(得分:2)

如果您有多个重复的密钥,只需要1 GROUP BY,如果您想先降低,那么ORDER BY ... ASC

SELECT * FROM table_a a WHERE a.rm = 2 GROUP BY a.reg ORDER BY a.date ASC
UNION
SELECT * FROM table_b b WHERE b.rm = 2 GROUP BY b.reg ORDER BY b.date ASC

我没有100%理解为什么你有两个不同的表用于相同的东西,也许你需要首先UNION然后GROUP BY:

SELECT * FROM (
    SELECT * FROM table_a
    UNION ALL
    SELECT * FROM table_b
) x
WHERE x.rm = 2
GROUP BY x.reg
ORDER BY x.date ASC

答案 1 :(得分:1)

试试这个:

select reg, min(date)
from (
    (select reg, rm, date from table_a)
    UNION
    (select reg, rm, date from table_b)
) union_tbl
where rm = 2
group by reg