如何从嵌套连接查询中进行选择

时间:2014-05-30 06:11:51

标签: php mysql

我有这两个查询,我想将它们连接在一起,以便让用户根据第二个查询过滤第一个查询

第一次查询:

SELECT t1 . * 
FROM car t1
left outer JOIN rent ON t1.carId = rent.carId
WHERE NOT 
EXISTS (

SELECT NULL 
FROM rent t2
WHERE t1.carId = t2.carId

)
OR not (
rent.startdate > '$to'
OR rent.enddate < '$from'
)

第二个查询:

SELECT carId,model,fuelconsumption,type,picture,color,price,region FROM  car WHERE model ='$m' OR type='$t' OR price='$p' OR color = '$c' ORDER BY model,type,price,color DESC

这两个查询分别给出了正确的答案

1 个答案:

答案 0 :(得分:0)

我不确定您的请求是什么,但是如果要合并这两个查询,则应该这样做:

select t1.*
from car t1
left outer join rent on t1.carId = rent.carId
where 
(
  not exists
  (
    select null
    from rent t2
    where t1.carId = t2.carId
  )
  or not
  (
    rent.startdate > '$to'
    or rent.enddate < '$from'
  )
)
and 
(
  model ='$m'
  OR type='$t'
  OR price='$p'
  OR color = '$c'
)
order by model,type,price,color desc