[英]MySQL CASE & INNER JOIN Together?
I have the following SQL Query. 我有以下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
But is it possible to put that INNER JOIN into a CASE? 但是有可能将INNER JOIN放入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.
我想要完成的是当isAvailable列的值为Yes时,然后获取额外的信息,否则不要抓住它。
I tried putting the INNER JOIN between a CASE statement but it didn't work. 我尝试将INNER JOIN放在CASE语句之间,但它没有用。
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. 子查询执行的分组操作
parking_lot_dates
表,我们做一个外在于和之间的连接parking_lots
为了表有记录,即使加入条件不满足 。 Learn about SQL joins . 了解SQL连接 。
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; WHERE
子句通过消除任何预期在parking_lots
没有匹配记录的结果来模仿INNER JOIN
的效果; 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: 也许你需要一个
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.