我想在CASE逻辑中使用Select子查询执行IN语句(MySQL方言一直在使用)
所以查询的想法是这样的:
select a.client_id,
(case when a.client_id in (select distinct a.client_id from account a
where a.display_name='b') then '1' else '0' end) as binary
from account a
group by a.client_id
order by a.client_id
它显示错误,所以我想知道它是如何被替换和重写的?
谢谢!
答案 0 :(得分:1)
问题是您的binary
列既不是聚合也不是GROUP BY
子句的成员。
您可以将case
复制到GROUP BY
,或将子查询替换为:
SELECT
a.client_id
, MAX(CASE WHEN b.client_id IS NOT NULL THEN 1 ELSE 0 END) as binary
FROM account a
LEFT OUTER JOIN account b
ON a.client_id=b.client_id AND b.display_name='b'
GROUP BY a.client_id
GROUP BY a.client_id
现在CASE
被推入MAX
聚合函数,可以通过检查显示名称为'b'
的其他客户端是否存在来检查是否存在# This is a registered user or guest
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable
def initialize(attributes = {})
super
@hex ||= SecureRandom.hex(4)
end
end
。外部联接。
答案 1 :(得分:1)
我认为你根本不需要子查询。试试这个:
select a.client_id,
case when a.display_name = 'b' then '1'
else '0' end as binary
from account a
group by a.client_id
order by a.client_id