加入表在laravel中创建一个重复条目

dl5txlt9  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(257)

我只想合并两个表的内容并基于id显示它。
两个表都有3个条目。
表a-取样顺序

Date Docname Products Quantity ID
1     A       A         1      1
2     B       B         2      1 
3     C       C         3      1

表b-代表性位置

Date Area lat long ID
 1    a    1   1   1
 2    b    2   2   1
 3    c    3   3   1

输出应该生成3行,其中所有表a列和表b列的id=specified id
我需要这样的输出

Date Docname product Quantity Area lat long
1      A       A       1       a    1   1
2      B       B       2       b    2   2
3      C       C       3       c    3   3

但是它会生成9行(3*3)并复制两个表中的行数。它的生成

Date Docname product Quantity Area lat long
1      A       A       1       a    1   1
2      B       B       2       b    2   2
3      C       C       3       c    3   3
1      A       A       1       a    1   1
2      B       B       2       b    2   2
3      C       C       3       c    3   3
1      A       A       1       a    1   1
2      B       B       2       b    2   2
3      C       C       3       c    3   3

梳理a*b中的行数-相对于id,我只需要3行。
查询-

$Report = DB::table('sampling_order')
             ->join('representativelocations','representativelocations.representativeid','=','sampling_order.representativeid')
             ->select('sampling_order.representativeid as representativeid',
             'sampling_order.date as date',
             'sampling_order.doctor_name as doctor_name',
             'sampling_order.products as products',
             'sampling_order.quantity as quantity',
             'representativelocations.latitude as latitude',
             'representativelocations.longitude as longitude',
             'representativelocations.area as area')
             ->whereBetween('sampling_order.date', [$Datefrom, $Dateto])
             ->where('sampling_order.representativeid','=',$Representativeid)->get();
mqkwyuun

mqkwyuun1#

我可以看到,在两个表中,all id是'1',所以在result中应该是3*3=9行。我猜你可能想要这个:
id产品区-a区-b区-c
第1篇第1篇第2篇第3篇
1\uuuuu b\uuuuu 2\uuuuuu 3\uuuuuuuuu 4
如果是的话。你需要加入三次。

SELECT * FROM A
LEFT JOIN (SELECT *, area AS area-A FROM B WHERE area = 'a' ) AS B ON B.id = A.id
LEFT JOIN (SELECT *, area AS area-B FROM B WHERE area = 'b' ) AS C ON C.id = A.id
LEFT JOIN (SELECT *, area AS area-C FROM B WHERE area = 'c' ) AS D ON D.id = A.id

希望这就是你想要的。

ix0qys7i

ix0qys7i2#

根据要求,我想你应该试着加入 date 不是 ID 如下所示。这会回来的 3 如您所料。

select so.date,so.Docname,so.products,so.Quantity,rl.Area,rl.lat,rl.long from Sampling_order AS so
INNER JOIN  Representative_locations as rl ON so.Date = rl.Date
WHERE so.ID = 1

根据需要更改表名和列名。

相关问题