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 this INNER JOIN in CASE? what I'm trying to accomplish is that when the value of the isAvailable column is Yes, then take additional information, otherwise don't take it.

I tried putting INNER JOIN between the CASE statement, but it did not work.

Thanks in advance.

+3
source share
2 answers

You cannot make a conditional join the way you want, but instead you can:

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)

A subquery performs a grouping operation on a table parking_lot_dates, and we make an outer join between this and the table parking_lotsto have records, even if the join condition is not satisfied. More on SQL joins .

WHERE INNER JOIN, , parking_lots, ; , .

+2

, . , HAVING - , :

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
0

All Articles