【问题标题】:MySQL : How to query two tables sequentially?MySQL:如何顺序查询两个表?
【发布时间】:2017-09-03 10:59:08
【问题描述】:

例如,
有两个表articles_1articles_2,它们的字段是一样的:

id
title
content
slug

当有一个表时,我可以这样查询一篇文章:

public function show($slug)
{
    $article = Article::findOrFail($slug);

    return view('show', compact('article'));
}

现在有两个表,想查询一篇文章,代码怎么写?

【问题讨论】:

  • 如果所有字段都相同,您能描述一下为什么要使用两个表吗?
  • 也许您应该先解决your first question 上的反馈,然后再针对同一问题提出更多问题。
  • @Tim Biegeleisen 谢谢,我已对您对该问题的评论投了票,我使用字符串而不是自动递增数字。

标签: mysql laravel


【解决方案1】:

你可以使用 UNION

$table1_items = \DB::table('articles_1')
            ->select(\DB::raw("id, title, content,slug"))

$table2_items  = \DB::table('software_items')
            ->select(\DB::raw("id, title, content,slug"))

$results = $table1_items->union($table2_items)->get();

【讨论】:

    【解决方案2】:

    您可以考虑在数据库层本身创建视图。视图将使用 UNION 来合并两个表中的结果。

    【讨论】:

      猜你喜欢
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      相关资源
      最近更新 更多