简体   繁体   中英

MySQL CASE & INNER JOIN Together?

I have the following SQL Query.

SELECT MIN(PLD.available_date) as 'FROM', MAX(PLD.available_date) as 'UNTIL', (
CASE
    WHEN DATEDIFF('2012-04-01', '2012-04-10') = (COUNT(PLD.available_date) - 1)
    THEN 'Yes'
    ELSE 'No'
END) as isAvailable, PL.*
FROM `parking_lot_dates` as PLD
INNER JOIN parking_lots as PL ON PLD.plid = PL.plid
WHERE PLD.available_date BETWEEN '2012-04-01' AND '2012-04-10'
GROUP BY PLD.plid

But is it possible to put that INNER JOIN into a CASE? what i'm trying to accomplish is that when the isAvailable column's value is Yes then grab the extra information otherwise don't grab it.

I tried putting the INNER JOIN between a CASE statement but it didn't work.

Thanks in advance.

You can't do a conditional join in the way you want, but you could instead:

SELECT PLD.FROM, PLD.UNTIL, IF(PLD.isAvailable, 'Yes', 'No') AS isAvailable, PL.*
FROM (
    SELECT   plid
      ,      MIN(available_date) AS `FROM`
      ,      MAX(available_date) AS `UNTIL`
      ,      DATEDIFF('2012-04-01', '2012-04-10') = COUNT(*) - 1 AS `isAvailable`
    FROM     parking_lot_dates
    WHERE    available_date BETWEEN '2012-04-01' AND '2012-04-10'
    GROUP BY plid
  ) AS PLD LEFT JOIN parking_lots AS PL ON (
    PLD.isAvailable AND PL.plid = PLD.plid
  )
WHERE NOT (PLD.isAvailable AND PL.plid IS NULL)

The subquery performs the grouping operation on the parking_lot_dates table, and we make an outer join between that and the parking_lots table in order to have records even when the join condition is not satisfied. Learn about SQL joins .

The WHERE clause imitates the effect of your INNER JOIN by eliminating any results for which there was not a matching record in parking_lots when one was expected; it can be omitted if you didn't actually want that behaviour.

It's not very clear what exactly you want. Perhaps a HAVING clause is all you need:

SELECT PL.*
FROM parking_lot_dates AS PLD
  INNER JOIN parking_lots AS PL 
    ON PLD.plid = PL.plid
WHERE PLD.available_date BETWEEN '2012-04-01' AND '2012-04-10'
GROUP BY PLD.plid
HAVING DATEDIFF('2012-04-01', '2012-04-10') = COUNT(PLD.available_date) - 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM