我想将以下2个查询组合为一个单一查询。
我查询了预订的住所。
SELECT some coluns
FROM residence r
JOIN project p ON p.ProjectId = r.ProjectId
LEFT OUTER JOIN residencetype rt ON r.ResidenceTypeId = rt.ResidenceTypeId
LEFT OUTER JOIN entity_milestone em ON (r.`Status`='BOOKED' AND em.ResidenceId = r.`ResidenceId`)
LEFT OUTER JOIN milestone m ON (em.`MilestoneId`=m.MilestoneId)
LEFT OUTER JOIN (builder_prospect bp ON r.builderProspectId = bp.id)
LEFT OUTER JOIN (builder_prospect bp ON r.builderProspectId = bp.id)
WHERE r.ProjectId =77 AND r.status='BOOKED';
我对未预订的住所进行查询。
SELECT some coluomns
FROM residence r
JOIN project p ON p.ProjectId = r.ProjectId
LEFT OUTER JOIN residencetype rt ON r.ResidenceTypeId = rt.ResidenceTypeId
LEFT OUTER JOIN entity_milestone em ON (r.`Status`='AVAILABLE' AND em.ResidenceTypeId=r.ResidenceTypeId)
LEFT OUTER JOIN milestone m ON (em.MilestoneId=m.MilestoneId)
LEFT OUTER JOIN builder_prospect bp ON r.builderProspectId = bp.id
WHERE r.ProjectId = 77 AND r.status='AVAILABLE';
如何组合这些查询并将其作为单个查询?
答案 0 :(得分:0)
使用union/union-all。确保所选的some_colums在字段名称和数据类型方面的查询中都相同
SELECT some_colums, r.status
FROM residence r JOIN project p ON p.ProjectId = r.ProjectId
LEFT OUTER JOIN residencetype rt ON r.ResidenceTypeId = rt.ResidenceTypeId
LEFT OUTER JOIN LEFT OUTER JOIN entity_milestone em ON (r.`Status`='BOOKED' AND em.ResidenceId = r.`ResidenceId`)
LEFT OUTER JOIN milestone m ON (em.`MilestoneId`=m.MilestoneId) LEFT OUTER JOIN (builder_prospect bp ON r.builderProspectId = bp.id)
LEFT OUTER JOIN (builder_prospect bp ON r.builderProspectId = bp.id)
WHERE r.ProjectId =77 AND r.status='BOOKED'
UNION
SELECT some_colums, r.status
FROM residence r JOIN project p ON p.ProjectId = r.ProjectId
LEFT OUTER JOIN residencetype rt ON r.ResidenceTypeId = rt.ResidenceTypeId
LEFT OUTER JOIN entity_milestone em ON (r.`Status`='AVAILABLE' AND em.ResidenceTypeId=r.ResidenceTypeId)
LEFT OUTER JOIN milestone m ON (em.MilestoneId=m.MilestoneId)
LEFT OUTER JOIN builder_prospect bp ON r.builderProspectId = bp.id
WHERE r.ProjectId = 77 AND r.status='AVAILABLE';
答案 1 :(得分:-1)
<强>更新强> 像这样?
SELECT r.*
FROM residence r JOIN project p ON p.ProjectId = r.ProjectId
LEFT OUTER JOIN residencetype rt ON
((r.`Status`='BOOKED' AND em.ResidenceId = r.`ResidenceId`)
OR (r.`Status`='AVAILABLE' AND em.ResidenceTypeId=r.ResidenceTypeId))
LEFT OUTER JOIN entity_milestone em ON em.ResidenceTypeId=r.ResidenceTypeId
LEFT OUTER JOIN milestone m ON em.MilestoneId=m.MilestoneId
LEFT OUTER JOIN builder_prospect bp ON r.builderProspectId = bp.id
WHERE r.ProjectId = 77 AND (r.status = 'AVAILABLE' or r.status = 'BOOKED')
<强> UPDATE2:强>
抱歉,r.status in (...)
无效!