我只想合并2个表的内容并根据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 =指定的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();
答案 0 :(得分:0)
根据要求,我认为您应该按以下方式尝试加入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
根据需要更改表名和列名。
答案 1 :(得分:0)
我看到的是,两个表中的所有Id均为“ 1”, 因此结果应为3 * 3 = 9行。 我想您可能想要这样:
id产品区域-A区域-B区域-C
1 ____ A ____ 1 ____ 2 _____ 3
1 ____ B ____ 2 ____ 3 _____ 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
希望这就是您想要的。