我有2个表格,其结构与此类似:
table:user
字段:id,active_office_address_id(可以是0)
table:user_address
字段:id,user_id,type(home,office)
用户可以拥有“家庭”地址(非强制性)和多个“办公室”地址。我有一个联接来获取用户地址,但是我希望如果用户有一个“家”地址来获取该地址,而不是“办公室”地址。
那么,如果存在,我怎样才能获得“归属”地址,并且只有在不存在“办公室”地址时才能获得。 (实际上,查询要复杂得多,并且连接在4-5个表上完成)
SELECT * FROM user LEFT JOIN user_address ON (user.id = address.user_id AND
(user_address.type = "home" OR user.active_office_address_id = user_address.id))
group by user.id
答案 0 :(得分:5)
您可以使用COALESCE()
并加入地址表两次:
SELECT user.id
,COALESCE(home.address, office.address) AS Address
FROM user
LEFT JOIN user_address AS home
ON user.id = home.user_id
AND home.type = "home"
LEFT JOIN user_address AS office
ON user.active_office_address_id = office.user_id
GROUP BY user.id
答案 1 :(得分:3)
两个左连接和一个case语句将为您提供所需的地址ID。
SELECT user.*,CASE WHEN home_addr.id IS NOT NULL THEN home_addr.id ELSE ofc_addr.id END AS addr_id
FROM user
LEFT JOIN user_address AS home_addr
ON (user.id = home_addr.user_id AND home_addr.type = 'home')
LEFT JOIN user_address AS ofc_addr
ON (user.active_office_address_id = ofc_addr.id)
您可以将此作为特定用户的子选项反馈:
SELECT * FROM user LEFT JOIN user_address
WHERE user.id = ?
AND user_address.user_id = user.id
AND user_address.id IN
(SELECT CASE WHEN home_addr.id IS NOT NULL THEN home_addr.id ELSE ofc_addr.id END AS addr_id
FROM user
LEFT JOIN user_address AS home_addr
ON (user.id = home_addr.user_id AND home_addr.type = 'home')
LEFT JOIN user_address AS ofc_addr
ON (user.active_office_address_id = ofc_addr.id)
WHERE user.id = ?)
这假设每个用户只存在一个家庭地址。
答案 2 :(得分:0)
至少在SQL Server中,不确定MySql,可以在order by子句中使用case
语句,例如:
order by user.id, case user_address.type when 'home' then 1 else 2 end, --additional ordering clauses here