我有以下几段代码:
$referrers_query =
select c.customers_id, c.customers_firstname, c.customers_lastname,
c.customers_email_address, c.customers_telephone, a.entry_street_address,
a.entry_city, a.entry_state, a.entry_country_id, n.countries_name,
a.entry_zone_id, a.entry_postcode, r.referrer_customers_id,
r.referrer_key, r.referrer_homepage, r.referrer_approved,
r.referrer_banned, r.referrer_commission from customers as c,
address_book as a, referrers as r, countries as n
where a.entry_country_id = n.countries_id and c.customers_id = r.referrer_customers_id
and a.address_book_id = c.customers_default_address_id order by c.customers_lastname;
我想做的是,而不是加入WHERE
子句,我想嵌套连接。
上面提到了五个数据库表。 客户,地址簿,推荐人,国家/地区。
但我不知道从哪里开始。这个问题的主要问题是使用上面的语句,我似乎从select中丢失了一些记录。这是因为有些记录正在使用'zone_id'= 0.修复此问题只是为0创建空白记录,但除此之外,我可以使用连接来修复此问题吗?
答案 0 :(得分:2)
使用显式JOIN
s:
SELECT c.customers_id, c.customers_firstname, c.customers_lastname,
c.customers_email_address, c.customers_telephone, a.entry_street_address,
a.entry_city, a.entry_state, a.entry_country_id, n.countries_name,
a.entry_zone_id, a.entry_postcode, r.referrer_customers_id,
r.referrer_key, r.referrer_homepage, r.referrer_approved,
r.referrer_banned, r.referrer_commission
FROM customers AS c
JOIN referrers AS r ON (c.customers_id = r.referrer_customers_id)
JOIN address_book AS a ON (a.address_book_id = c.customers_default_address_id)
JOIN countries AS n ON (a.entry_country_id = n.countries_id)
ORDER BY c.customers_lastname
如果您希望同时获取区域表中的信息,则需要添加LEFT JOIN
,如下所示:
SELECT c.customers_id, c.customers_firstname, c.customers_lastname,
c.customers_email_address, c.customers_telephone, a.entry_street_address,
a.entry_city, a.entry_state, a.entry_country_id, n.countries_name,
a.entry_zone_id, a.entry_postcode, r.referrer_customers_id,
r.referrer_key, r.referrer_homepage, r.referrer_approved,
r.referrer_banned, r.referrer_commission
FROM customers AS c
JOIN referrers AS r ON (c.customers_id = r.referrer_customers_id)
JOIN address_book AS a ON (a.address_book_id = c.customers_default_address_id)
JOIN countries AS n ON (a.entry_country_id = n.countries_id)
LEFT JOIN {zones table name} AS z ON (z.{zones id column name} = a.entry_zone_id)
ORDER BY c.customers_lastname
并将要选择的列添加到查询的顶部。 LEFT JOIN
始终返回左表(列出的第一个)的结果,如果右表中没有匹配,则返回右表的列的NULL
。