从多个表中检索数据不起作用

时间:2019-04-18 11:51:25

标签: sql

我有三个桌子

quiz:              activetruck:
id                 id   
name               name
origin             origin
destination        destination
total_trucks       total_trucks
material_type      scheduled_date
scheduled_date     offered_price
offered_price      owner_id
owner_id           subject_id
subject_id

我运行了该查询以从两个表中提取公共数据

Select * from quiz as cq, activetruck as ca
where cq.origin=ca.origin and cq.destination=ca.destination and 
cq.subject_id=ca.subject_id and cq.total_trucks<=ca.total_trucks;

有第三个桌子供应商,供应商通过 owner_id

连接到活动卡车
columns of suppliers are:
user_id
supplier_name
supplier_company_name
supplier_email
supplier_gst
supplier_pan
supplier_address
supplier_origin
supplier_service

我想获取供应商的所有详细信息,其中activetruck.owner_id = provider.user_id 我尝试运行它,但是没有用

Select * from classroom_quiz as cq, classroom_activetruck as ca, classroom_supplier as cs 
where cq.origin=ca.origin and cq.destination=ca.destination and
 cq.subject_id=ca.subject_id and cq.total_trucks<=ca.total_trucks and
 ca.owner_id=cs.user_id;

1 个答案:

答案 0 :(得分:1)

您需要使用左外部联接。更多信息here

activetruck和供应商上的左外部联接将返回匹配的供应商详细信息,但是在没有匹配项的情况下,仍将返回activetruck行。您的查询正在加入,activetruck与供应商匹配,但如果没有匹配,则不返回任何内容。

SELECT *
FROM classroom_quiz AS cq
INNER JOIN classroom_activetruck ca ON cq.origin = ca.origin
    AND cq.destination = ca.destination
    AND cq.subject_id = ca.subject_id
    AND cq.total_trucks <= ca.total_trucks
LEFT OUTER JOIN classroom_supplier cs ON ca.owner_id = cs.user_id;