1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > php中连接两个值 php - 如何从两个表的连接中选择一个值? - SO中文参考 - www.soinside.com...

php中连接两个值 php - 如何从两个表的连接中选择一个值? - SO中文参考 - www.soinside.com...

时间:2020-12-19 15:19:40

相关推荐

php中连接两个值 php - 如何从两个表的连接中选择一个值? - SO中文参考 - www.soinside.com...

我想在LaravelMySQL中实现一些功能, 但似乎没有找到正确的解决方案. 我可以用子查询来实现我想要的东西, 但是我被告知他们没有联接那么高效. 而且,我将不得不把这个解决方案转换到EloquentQuery Builder中,而我使用子查询和联合的方式似乎不容易转换。

我想做的是从两个可能的表中选择一条记录,基于的是 created_at 行的日期。我想加入这个 created_at 值,在我的用户表中新建一列,称为 started_at. 下面是一些示例数据,以及我如何用两个可能的表的子查询union来实现查询,我可以从这两个表中获取数据。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, '-04-29'),

(2, 2, 7, 4, '-03-28'),

(3, 3, 4, 6.99, '-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, '-04-27'),

(2, 2, 3, 12, 2, '-03-29'),

(3, 3, 3, 6, 3, '-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 表。

如何通过连接来实现?任何帮助都将是非常感激的.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。