2015-07-20 58 views
-1

好的,所以我在MySQL中編寫SQL代碼以從兩個不同的表中獲取客戶名並將其顯示給用戶。MySQL中CASE表達式的問題:操作數應該包含1列

我有案設置在我的SQL,但是當我運行它,我得到的消息

"Error Code: 1241. Operand should contain 1 column(s)."

的語法是從「帳戶」表中提取信息,顯示不存在於行「交易「表,並需要按賬戶持有人類型對其進行分類,無論是企業還是個人。並顯示個人的姓和名(如果該賬戶由個人持有)或公司名稱(如果由企業持有)。

下面是我的語法給錯誤:

use bank; 

select acct.account_id as "Account ID", 
case (select cust_id from account 
    where acct.cust_id = ind.cust_id) 
    when acct.cust_id = ind.cust_id 
    then (select fname, ' ', lname from individual ind) 
    when businessacct.cust_id = bus.cust_id 
    then (select name from business bus) 
    end cust_type, 
acct.cust_id as "Customer ID", 
acct.last_activity_date as "Date last active", 
acct.avail_balance as "Available Balance", 
(select concat(fname, ' ', lname) 
    from employee 
    where emp_id = acct.open_emp_id) as 'Opening Employee' 
from account acct, 
    individual ind, 
    business bus 
where acct.account_id not in (select account_id from transaction) 
order by acct.cust_id; 

我知道沒有人能真正運行這個無我有表,但任何人都可以引導我在正確的方向?

+0

http://stackoverflow.com/questions/9588015/how-do-i-use-properly-case-when-in-mysql – Drew

回答

1

所以在你的查詢中有幾個問題;您沒有正確使用大小寫表達式,並且存在嚴重的連接問題。即使您更正了case表達式中的問題,查詢也很可能無法按預期運行,因爲您不以任何有意義的方式加入表。

既然你不同意任何模式或樣品數據這只是一種猜測,查詢可能應該是什麼樣子:

select 
    acct.account_id as "Account ID", 
    case 
     when acct.cust_id = ind.cust_id then concat(ind.fname, ' ', ind.lname) 
     when acct.cust_id = bus.cust_id then bus.name 
    end cust_type, 
    acct.cust_id as "Customer ID", 
    acct.last_activity_date as "Date last active", 
    acct.avail_balance as "Available Balance", 
    concat(emp.fname, ' ', emp.lname) as 'Opening Employee' 
from account acct 
join employee emp on emp.emp_id = acct.open_emp_id 
left join individual ind on acct.cust_id = ind.cust_id 
left join business bus on acct.cust_id = bus.cust_id 
where acct.account_id not in (select account_id from transaction) 
order by acct.cust_id; 

你也許可以用這個代替整個案件表達:

coalesce(bus.name, concat(ind.fname, ' ', ind.lname)) cust_type, 

哪個會選擇bus.name是否有一個(意味着它是一個業務)或使用個人的值代替。

相關問題