我正在尝试在Laravel / MySQL中实现某些目标,似乎无法为解决方案指明正确的方向。我可以通过子查询实现我想要的功能,但是有人告诉我它们不如联接有效。而且,我将不得不将解决方案转换为Eloquent / Query Builder,而使用子查询和联合的方法似乎并不容易转换。
我要根据行的created_at
日期从两个可能的表中选择一行。我想将此created_at
值与我的users表一起添加为名为started_at
的新列。以下是一些示例数据,以及如何使用两个可能的表的子查询/联合来实现查询,我可以从中获取数据:
CREATE TABLE users (
id INTEGER,
first_name TEXT,
last_name TEXT
);
INSERT INTO users (id, first_name, last_name)
VALUES
(1, 'Craig', 'Smith'),
(2, 'Bill', 'Nye'),
(3, 'Bloop', 'Blop');
CREATE TABLE old_activity (
id INTEGER,
user_id INTEGER,
firm_id INTEGER,
amount INTEGER,
created_at DATE
);
INSERT INTO old_activity (id, user_id, firm_id, amount, created_at)
VALUES
(1, 1, 3, 5.24, '2019-04-29'),
(2, 2, 7, 4, '2019-03-28'),
(3, 3, 4, 6.99, '2019-04-28');
CREATE TABLE new_activity (
id INTEGER,
user_id INTEGER,
firm_id INTEGER,
plays INTEGER,
saves INTEGER,
created_at DATE
);
INSERT INTO new_activity (id, user_id, firm_id, plays, saves, created_at)
VALUES
(1, 1, 3, 10, 1, '2019-04-27'),
(2, 2, 3, 12, 2, '2019-03-29'),
(3, 3, 3, 6, 3, '2019-04-27');
CREATE TABLE firms (
id INTEGER,
name TEXT
);
INSERT INTO firms (id, name)
VALUES
(1, 'apple'),
(2, 'banana'),
(3, 'orange');
select
id,
first_name,
last_name,
(select created_at from old_activity
where user_id = users.id
union
select created_at from new_activity
where user_id = users.id
order by created_at asc
limit 1) as started_at
from users
查询应仅返回两个created_at
表之一中特定用户的最早的activity
。
如何通过联接实现此目标?任何帮助,将不胜感激。
答案 0 :(得分:0)
嗯。 。 。您可以随时使用窗口功能:
select u.*, a.*
from users u left join
(select a.*,
row_number() over (partition by a.user_id order by a.created_at desc) as seqnum
from ((select oa.* from old_activity oa) union all
(select na.* from new_activity na)
) a
) a
on a.user_id = a.id and a.seqnum = 1