需要添加SQL Union查询

时间:2014-07-25 13:42:29

标签: mysql sql

我有一个查询,我检查登录的人是否作为所有者或居民连接到公寓(单位)。它看起来如下:

select m.* from member m
inner join unit_contract_member ucm on ucm.member_id = m.id
inner join unit_contract uc on uc.id = ucm.contract_id
inner join unit u on u.id = uc.unit_id
where m.usr = _usr
and m.pwd = _pwd
and u.community_id = _communityId
and m.active = true
and uc.active = true

union all

select m.* from member m
inner join unit_owner uo on uo.member_id = m.id
inner join unit u on u.id = uo.unit_id
where m.usr = _usr
and m.pwd = _pwd
and u.community_id = _communityId
and m.active = true;

此查询正常。但是,我现在需要添加一个拥有授权成员的公寓的可能性(几乎是另一种类型的所有者),理论上,查询看起来像这样(在查询末尾添加了部分):

select m.* from member m
inner join unit_contract_member ucm on ucm.member_id = m.id
inner join unit_contract uc on uc.id = ucm.contract_id
inner join unit u on u.id = uc.unit_id
where m.usr = _usr
and m.pwd = _pwd
and u.community_id = _communityId
and m.active = true
and uc.active = true

union all

select m.* from member m
inner join unit_owner uo on uo.member_id = m.id
inner join unit u on u.id = uo.unit_id
where m.usr = _usr
and m.pwd = _pwd
and u.community_id = _communityId
and m.active = true;

union all

select m.* from member m
inner join unit_authorized_member uam on uam.member_id = m.id
inner join unit u on u.id = uam.unit_id
where m.usr = _usr
and m.pwd = _pwd
and u.community_id = _communityId
and m.active = true;

然而,最后一次UNION ALL剂量发挥良好并且引发错误。我该怎么做才能获得这个预期的功能?有什么想法吗?

希望有人在SQL上比我更好。但是因为你的平均獾是,我猜不会太难找到:)

鲍勃

1 个答案:

答案 0 :(得分:4)

摆脱and m.active = true;

末尾的分号

我在我的服务器上用一些示例数据对此进行了测试,并且分号因为'

附近的错误而将其抛出
select m.* from member m
inner join unit_contract_member ucm on ucm.member_id = m.id
inner join unit_contract uc on uc.id = ucm.contract_id
inner join unit u on u.id = uc.unit_id
where m.usr = _usr
and m.pwd = _pwd
and u.community_id = _communityId
and m.active = true
and uc.active = true

union all

select m.* from member m
inner join unit_owner uo on uo.member_id = m.id
inner join unit u on u.id = uo.unit_id
where m.usr = _usr
and m.pwd = _pwd
and u.community_id = _communityId
and m.active = true

union all

select m.* from member m
inner join unit_authorized_member uam on uam.member_id = m.id
inner join unit u on u.id = uam.unit_id
where m.usr = _usr
and m.pwd = _pwd
and u.community_id = _communityId
and m.active = true