3

我有以下 SQL 查询。

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

但是是否可以将 INNER JOIN 放入 CASE 中?我想要完成的是,当 isAvailable 列的值为 Yes 时,获取额外的信息,否则不要获取它。

我尝试将 INNER JOIN 放在 CASE 语句之间,但没有奏效。

提前致谢。

4

2 回答 2

2

您不能以您想要的方式进行条件连接,但您可以:

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)

子查询对表执行分组操作parking_lot_dates,我们在该表和表之间进行外连接,以便在不满足parking_lots连接条件时也有记录。了解SQL 连接

该条款通过消除预期结果中没有匹配记录的任何结果来WHERE模仿您的效果;如果您实际上并不想要这种行为,则可以省略它。INNER JOINparking_lots

于 2012-05-12T07:34:07.450 回答
0

目前还不是很清楚你到底想要什么。也许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
于 2012-05-12T07:59:40.813 回答