【发布时间】:2020-05-06 10:14:45
【问题描述】:
我正在尝试在 Laravel/MySQL 中实现某些目标,但似乎无法为解决方案指明正确的方向。我可以通过子查询来实现我正在寻找的东西,但我被告知它们不如连接有效。而且,我将不得不将此解决方案转换为 Eloquent/Query Builder,而我使用子查询和联合的方式似乎并不容易转换。
我要做的是根据行的created_at 日期从两个可能的表中选择一行。我想将这个created_at 值与我的用户表作为一个名为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
查询应该只返回两个activity 表之一中特定用户的最旧created_at。
如何通过加入实现这一目标?对此的任何帮助将不胜感激。
【问题讨论】: