我有查询在多个表中查询特定列(确切地说是3个表),但我没有得到结果。
简而言之,这就是我想要实现的目标:
SELECT tblhosting.id,tblhosting.domain,tblhosting.userid,tblcoupons.coupon
WHERE tblhosting.packageid = tblproducts.id AND tblhosting.domainstatus ='Active'
AND(tblproducts.type ='hostingaccount' 或者tblproducts.type ='server')
AND tblcoupons.serviceid = tblhosting.id
但是从tblhosting返回所有行条件满足条件,并且tblcoupons.coupon WHERE tblhosting.id = tblcoupons.serviceid
查询如下:
SELECT tblhosting.id as tblhostingID, tblhosting.domain, tblhosting.userid, tblcoupons.coupon
FROM tblhosting, tblproducts
RIGHT JOIN tblcoupons ON id = tblcoupons.serviceid
WHERE tblhosting.userid =1
AND tblhosting.packageid = tblproducts.id
AND tblhosting.domainstatus = 'Active'
AND (tblproducts.type = 'hostingaccount'
OR tblproducts.type = 'server');
优惠券|状态| userid |服务ID
coupon1 没用过 空值 1
coupon2 没用过 空值 NULL
coupon3 没用过 空值 NULL
coupon4 没用过 空值 NULL
修改
如果分配了以下查询,我已成功返回tblhosting和优惠券中的所有行,但我不知道如何添加我的WHERE部分或包含我的tblproducts表以使用优惠券返回我的tblhosting中的所有行,如果未分配则返回NULL满足条件:
AND tblhosting.packageid = tblproducts.id
AND tblhosting.domainstatus = 'Active'
AND (tblproducts.type = 'hostingaccount'
OR tblproducts.type = 'server');
查询返回tblhosting和优惠券中的所有行(如果已分配:
)SELECT tblhosting.id AS HostingID, tblhosting.userid AS UserID, tblhosting.domain AS HostingDomain, tblcoupons.coupon AS Coupon
FROM tblhosting
LEFT JOIN tblcoupons ON tblhosting.id = tblcoupons.serviceid
WHERE tblhosting.userid =1;
编辑2
我是否只能使用LEFT JOIN语句来包含两个表?
我有以下查询,它返回正确的结果,具体取决于用户和WHERE子句:
SELECT tblhosting.id AS HostingID, tblhosting.userid AS UserID, tblhosting.domain AS HostingDomain, tblcoupons.coupon AS Coupon
FROM tblhosting
LEFT JOIN tblcoupons ON tblhosting.id = tblcoupons.serviceid
LEFT JOIN tblproducts ON tblproducts.id = tblhosting.packageid
WHERE tblhosting.userid =1
AND tblhosting.domainstatus = 'Active'
AND (
tblproducts.type = 'hostingaccount'
OR tblproducts.type = 'server'
OR tblproducts.type = 'reselleraccount'
);
答案 0 :(得分:2)
您正朝着正确的方向前进,但是您正在混合连接样式,这将使查询变得复杂。您还没有明确在示例查询的id
子句中来自哪个表ON
。
当我查询我希望一个表中的所有行以及另一个表中匹配的行时,我总是以表格形式启动FROM
,我想要所有行。我喜欢将其视为“驱动”该表中的查询。从那里,LEFT OUTER JOIN
到您只想要匹配记录的另一个表。此外,如果来自第三个表的查询存在条件,那么您可以安全地INNER JOIN
,因为记录将根据它进行过滤。
总而言之,你最终会得到类似的东西:
SELECT
tblhosting.id, tblhosting.domain, tblhosting.userid, tblcoupons.coupon
FROM
tblhosting
INNER JOIN tblproducts ON tblhosting.packageid = tblproducts.id
LEFT OUTER JOIN tblHosting ON tblProducts.id = tblcoupons.serviceid
WHERE
tblhosting.domainstatus = 'Active'
AND (tblproducts.type = 'hostingaccount' OR tblproducts.type = 'server')
这里我们过滤WHERE
子句中的记录,其他所有内容都在我们的FROM
子句中得到了整齐处理。当你仔细阅读这篇文章时,会非常清楚地了解哪些表格以及它们之间的关系。