MySql 根据列标准明确地连接行
MySql joining rows distinctly based on column criteria
我有一个 table 1,我想加入另一个 table 2,table 2 有不止一行不同的活动,所以我想做什么如果故事 2 的列具有读写活动,那么就是在加入时消除重复。如果该行同时具有两者,则仅显示具有写入 activity 和日期的行,如果其他行除了读取之外没有其他活动,则日期列显示为空,行应该是不同的
Table 1
id | labref
------------------
1 | 123
2 | 456
3 | 789
4 | 1011
5 | 1213
------------------
Table 2
id | labref | Activity | date
-------------------------------
1 | 123 | read | 29
2 | 123 | Write | 30
3 | 456 | Write | 31
4 | 789 | read | 04
5 | 1213 | read | 29
6 | 1011 | read | 04
7 | 1011 | Write | 05
-------------------------------
结果Table
id | labref | Activity | date
-------------------------------
1 | 123 | Write | 30
2 | 456 | Write | 31
3 | 789 | read | NULL
4 | 1213 | read | NULL
5 | 1011| Write | 05
-------------------------------
关于我如何实现这个的任何建议
select t2.id,t2.labref,
case when t2.activity in ('read','write') Then t2.activity ='write'
when t2.activity ='read' then t2.date =null
end as activity,
max(t2.date)
from table1 t1
inner join table2 t2 on t1.id = t2.id
group by t2.labref
也许是这个?
SELECT
t1.labref,
IFNULL(t2bis.Activity, t2.Activity),
t2bis.Date
FROM table1 t1
LEFT JOIN table2 t2 ON t2.labref = t1.labref
AND t2.Activity = 'read'
LEFT JOIN table2 t2bis ON t2bis.labref = t1.labref
AND t2bis.Activity = 'write'
说明
- 您
LEFT JOIN
表 2 的副本只有读取的值
- 你
LEFT JOIN
table2 的另一个副本只有写入值
对于activity:您显示所有行的labref,如果没有写入,则显示读取(如果没有读取,则显示null)
对于日期:只有有write才会显示日期activity,所以你显示的是write table2副本的date列。
IFNULL()
如果不是NULL
则显示第一个表达式,否则显示第二个
我有一个 table 1,我想加入另一个 table 2,table 2 有不止一行不同的活动,所以我想做什么如果故事 2 的列具有读写活动,那么就是在加入时消除重复。如果该行同时具有两者,则仅显示具有写入 activity 和日期的行,如果其他行除了读取之外没有其他活动,则日期列显示为空,行应该是不同的
Table 1
id | labref
------------------
1 | 123
2 | 456
3 | 789
4 | 1011
5 | 1213
------------------
Table 2
id | labref | Activity | date
-------------------------------
1 | 123 | read | 29
2 | 123 | Write | 30
3 | 456 | Write | 31
4 | 789 | read | 04
5 | 1213 | read | 29
6 | 1011 | read | 04
7 | 1011 | Write | 05
-------------------------------
结果Table
id | labref | Activity | date
-------------------------------
1 | 123 | Write | 30
2 | 456 | Write | 31
3 | 789 | read | NULL
4 | 1213 | read | NULL
5 | 1011| Write | 05
-------------------------------
关于我如何实现这个的任何建议
select t2.id,t2.labref,
case when t2.activity in ('read','write') Then t2.activity ='write'
when t2.activity ='read' then t2.date =null
end as activity,
max(t2.date)
from table1 t1
inner join table2 t2 on t1.id = t2.id
group by t2.labref
也许是这个?
SELECT
t1.labref,
IFNULL(t2bis.Activity, t2.Activity),
t2bis.Date
FROM table1 t1
LEFT JOIN table2 t2 ON t2.labref = t1.labref
AND t2.Activity = 'read'
LEFT JOIN table2 t2bis ON t2bis.labref = t1.labref
AND t2bis.Activity = 'write'
说明
- 您
LEFT JOIN
表 2 的副本只有读取的值 - 你
LEFT JOIN
table2 的另一个副本只有写入值
对于activity:您显示所有行的labref,如果没有写入,则显示读取(如果没有读取,则显示null)
对于日期:只有有write才会显示日期activity,所以你显示的是write table2副本的date列。
IFNULL()
如果不是NULL
则显示第一个表达式,否则显示第二个