SQL如果连接不匹配,则加入其他内容

时间:2011-04-12 17:16:44

标签: sql join

措辞不好因为我是SQL中的新操作,假设我有一个东西方地区的表,另一个表有一个名为address_state的字段。我希望能够加入address_state的UCASE等于state_abbreviation或state_name

EG:

SELECT orders.total_value, territories.territory FROM orders 
INNER JOIN tblCanadianTerritories ON 
UCASE(orders.technical_address_state) = tblCanadianTerritories.state 
OR 
tblCanadianTerritories ON 
UCASE(orders.technical_address_state) = tblCanadianTerritories.name

WHERE UCASE(orders.technical_address_country) = "CANADA"

编辑:

已经找到两种可能的解决方案:

SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer, tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON 
UCASE(so_order.technical_address_state) = tblCanadianTerritories.state   
OR
UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC

OR

SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer, 

tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) = 

tblCanadianTerritories.state   
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC
UNION 
SELECT so_order.id, so_order.date_entered,so_order.check_if_new_customer, 

tblCanadianTerritories.territory, so_order.total_value FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) = 

tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered;

但他们似乎都找回了不同的结果。

2 个答案:

答案 0 :(得分:4)

试试这个:

SELECT orders.total_value, territories.territory 
    FROM orders AS so_order INNER JOIN tblCanadianTerritories 
        ON (
            UCASE(so_order.technical_address_state) = tblCanadianTerritories.state 
            OR 
            UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
             )
WHERE UCASE(so_order.technical_address_country) = "CANADA"

如果您想使用UNION,请尝试:

SELECT orders.total_value, territories.territory 
    FROM orders AS so_order  INNER JOIN tblCanadianTerritories 
        ON UCASE(so_order.technical_address_state) = tblCanadianTerritories.state 
WHERE UCASE(so_order.technical_address_country) = "CANADA"
UNION
SELECT orders.total_value, territories.territory 
    FROM orders AS so_order  INNER JOIN tblCanadianTerritories 
        ON UCASE(so_order.technical_address_state) = tblCanadianTerritories.name 
WHERE UCASE(so_order.technical_address_country) = "CANADA"

答案 1 :(得分:2)

您不需要单独的加入。试试这个:

SELECT o.total_value, territories.territory 
FROM orders AS o
INNER JOIN tblCanadianTerritories AS ct ON 
UCASE(o.technical_address_state) = ct.state 
OR 
UCASE(o.technical_address_state) = ct.name
WHERE UCASE(o.technical_address_country) = "CANADA"

(现在有了别名)