laravel - 交叉连接不返回所有列

时间:2018-05-06 10:17:46

标签: php sql laravel

╔═══╦══════════════╦═════════════╗
║   ║id            ║name         ║
╠═══╬══════════════╬═════════════╣
║   ║ 1            ║a1           ║
║   ║ 2            ║b1           ║
║   ║ 3            ║b2           ║
║   ║ 4            ║c1           ║
║   ║ 5            ║c2           ║
╚═══╩══════════════╩═════════════╝

这是我在mysql中的表

在mysql中执行此查询:

select * from (select * from courses where name like 'a%') as t1 cross join (select * from courses where name like 'b%') as t2 cross join (select * from courses where name like 'c%') as t3

返回:

enter image description here

然而,当我尝试在larael上运行它以显示结果时,我得到了不同的结果。

这就是我在laravel中执行的方式:

$posts = DB::select(DB::raw("select * from (select * from courses where name like 'a%') as t1 cross join (select * from courses where name like 'b%') as t2 cross join (select * from courses where name like 'c%') as t3"));

这是$posts返回的内容:

[{"id":4,"name":"c1"},{"id":4,"name":"c1"},{"id":5,"name":"c2"},{"id":5,"name":"c2"}]

如果我们将它与mysql上返回的原始结果进行比较,它只会返回查询的最后两列查询。

知道如何获得完整的结果吗?

1 个答案:

答案 0 :(得分:1)

t3会覆盖t1t2的值。你必须使用别名:

select t1.id as t1_id, t1.name as t1_name,
    t2.id as t2_id, t2.name as t2_name,
    t3.id as t3_id, t3.name as t3_name

您还应该使用query builder而不是原始SQL。