0

我有以下代码:

$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子句连接,而是嵌套连接。

上面提到了五个数据库表。客户、地址簿、推荐人、国家、地区。

但我不知道从哪里开始。这样做的主要问题是使用上述语句,我似乎从选择中丢失了一些记录。这是因为有些记录使用 'zone_id' = 0。对此的解决方法是简单地为 0 创建一个空白记录,但除此之外,我可以使用连接来解决这个问题吗?

4

1 回答 1

2

用显式JOINs 编写的查询:

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

并将您要选择的列添加到查询的顶部。ALEFT JOIN总是从左表(列出的第一个)返回结果,如果右表中没有匹配项,它会NULL为右表的列返回 s。

于 2012-10-24T18:36:17.840 回答