【问题标题】:How to get all data from one table and replace the value from another table if exist?如何从一个表中获取所有数据并替换另一个表中的值(如果存在)?
【发布时间】:2018-03-09 15:35:04
【问题描述】:

我有两张桌子。

表 1

| id         | name        | description  |
|:-----------|------------:|:------------:|
| 1          | abc         |     qqq
| 2          | efg         |     qqq
| 3          | hij         |     wqq
| 4          | klm         |     c
| 5          | nop         |     de
| 6          | qrs         |     aa

表 2

| id         | quantity    |
|:-----------|------------:|
| 1          | 10          | 
| 2          | 21          |  

我想显示表 1 中的所有记录,然后从表 2 中获取数量。如果表 1 中的 id 存在于表 2 中,那么数量值将如表 2 中所列,否则我将设置 0对于表 2 中未找到的 id。

我试过了

DB::table('table1')
->leftJoin('table2', function($join) use($option){
$join->where('option', $option)
->on('table1.id', '=', 'table2.id');
})
->select(table1.*','table2.*')
->get();

它返回 table1 中的所有项目,但它只获取 table2 中存在的 id 其他将返回 null。

我该怎么做才能得到预期的结果?

【问题讨论】:

    标签: mysql laravel laravel-query-builder


    【解决方案1】:
    SELECT tab1.*, ifnull(tab2.quantity, 0) AS qty
    FROM tab1
    LEFT JOIN tab2 ON tab1.id = tab2.id
    

    【讨论】:

    • 好的,谢谢。我不应该从表 2 中选择全部,我认为现在一切正常。
    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 2014-01-31
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多