【问题标题】:Laravel 8 Inner Join Two TablesLaravel 8 内部连接两个表
【发布时间】:2021-04-29 04:20:59
【问题描述】:

我正在尝试从我的 Laravel 数据库中的两个表中获取不同的列,我是 joins 新手,但是按照文档我认为我的语法是正确的,除了我收到以下错误:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in on clause is ambiguous (SQL: select `data_source_one`.`event_count`, `data_source_two`.`sessions` from `data_source_one` inner join `data_source_two` on `created_at` >= `2021-01-11 10:57:45`)

我有两张桌子:

  • data_source_one
  • data_source_two

每个表都有 Laravel created_at 列,一个表有 sessions 列,另一个有 event_count,我有查询前 14 天的数据。所以不知道为什么它无法获取数据?

我的 PHP 是:

public function getSources(Request $request)
{

    $data = DB::table('data_source_one')
          ->join('data_source_two', 'created_at', '>=', Carbon::now()->subDays(14))
          ->select('data_source_one.event_count', 'data_source_two.sessions')
          ->get();

    return response()->json($data, 200);

}

【问题讨论】:

  • created_at 在两个表中都存在,所以你必须像这样添加表:data_source_two.created_at
  • 它说当我有->join('data_source_two.created_at', '>=', Carbon::now()->subDays(14))created_at 列不存在,但它确实存在
  • 无论如何,在我看来,您正在使用 on 语句作为 where 语句...

标签: php mysql laravel


【解决方案1】:

如错误消息中所示,“created_at”列不明确,因为它存在于两个表中。 所以你必须指定你指的是哪个“created_at”。

可能是这样的:

$data = DB::table('data_source_one as DSO')
      ->join('data_source_two as DST', //here, join your two tables by a common column )
      ->select('DSO.event_count', 'DST.sessions')
      ->where('DST.created_at', '>=', Carbon::now()->subDays(14))
      ->get();

【讨论】:

  • 奇怪的是这会返回错误:Column not found: 1054 Unknown column '2021-01-11 11:12:21' 好像它正在使用列名的值?
  • @RyanHolton 这并不奇怪,应该使用 on 语句来使关系工作,您想将其用作 where 语句。表中有本地键和外键吗?
  • @RyanHolton 是的,因为您使用连接作为 where。您必须通过一个公共列连接您的两个表,然后像这样添加 where 子句:->where('DST.created_at', '>=', Carbon::now()->subDays(14))跨度>
  • 两个表都有默认的id 列,除此之外,我只有created_atupdated_at 每个表都相同。所以尝试这样做:->join('data_source_two as DST', 'id'),为什么这不起作用?我可以不使用id 列吗?
  • 我从每个角度攻击这个我都会得到某种Integrity constraint violation: 1052 Column COLUMN NAME in on clause is ambiguous
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
  • 2018-01-15
  • 2017-06-23
  • 2011-01-28
  • 2010-12-17
相关资源
最近更新 更多