2014-09-19 114 views
0

我希望你們可以幫我在SQL,因爲我是一個新手iN的SQL。我的問題是,代碼沒有給出預期的輸出,我不知道如何解決這個問題,儘管我已經通過書籍和在線資源進行搜索。我有2個表(客戶& order_status)。任務是:爲什麼我如果沒有給出預期的輸出? (mySQL)

(1) select c_id,lname,address,city,description where c_id > 3 
(2) select c_id,lname,address,o_status,item_total,remarks and update description to 'black' where c_id =3 
(3)if item_total > 2, select o_status,item_total. ELse select o_status,item_total,remarks,order_no and update remarks to 'set' 

所以,這裏是代碼:

#drop procedure if exists usp_GetAnything; 
delimiter // 
create procedure usp_GetAnything() 
begin 
declare total int ; 
select total = item_total 
from order_status; 


select c_id,lname,address,city,description 
from customer 
where c_id > 3; 

select c.c_id,c.lname,c.address,o.o_status,o.item_total,o.remarks,c.description 
from customer c,order_status o 
where c.c_id=o.c_id; 
update customer 
set description = 'black' 
where c_id = 3; 

if (total > 2) then 
    select o_status,item_total,remarks 
    from order_status 
    where item_total = total; 
else 
    select o_status,item_total,remarks,order_no 
    from order_status 
    where item_total = total; 
    update order_status 
    set remarks = 'set'; 
end if; 
end 

我期待的輸出以獲取每一行ITEM_TOTAL。如果item_total> 2,它只會選擇,否則,它會更新備註。每個c_id有不同的no。 item_total。

+1

您使用「If」語句是錯誤的。它必須在「選擇」語句內。 – 2014-09-19 01:25:02

+0

@KenanZahirovic item_total的變量聲明,是真的嗎? – user4053201 2014-09-19 01:54:49

回答

0

您的代碼有點混亂,所以我會盡量幫助您一次完成一件作品。

你的(1),其中c_id> 3,這樣做的目的是什麼,這將給所有ID大於3的客戶,但是可以。 格式化查詢的可讀性也是養成習慣的好方法。另外, USE表別名,尤其是當您進入更長的表名引用時,可以更輕鬆地 分別加入/鏈接/獲取字段/ where/group。即使一張桌子。

select 
     c.c_id, 
     c.lname, 
     c.address, 
     c.city, 
     c.description 
    from 
     customer c 
    where 
     c.c_id > 3; 

您的(2a)。您的查詢會根據客戶的ID從 進行從客戶表到訂單狀態的簡單連接。這是可以的,但它也會返回所有有訂單的客戶, ,並且如果某人有多個訂單,它會向客戶展示他們的訂單。 此外,儘量養成在表中使用JOIN條件而不是在WHERE子句中隱含的連接 的習慣。當您需要進入左/右連接條件時,它更容易。

select 
     c.c_id, 
     c.lname, 
     c.address, 
     o.o_status, 
     o.item_total, 
     o.remarks, 
     c.description 
    from 
     customer c 
     JOIN order_status o 
      ON c.c_id = o.c_id; 

現在,如果您只關心特定客戶,請爲所述客戶ID添加WHERE子句。

你的(2b)的部件的描述更新爲 '黑色',其中C_ID = 3,即是確定

update customer 
    set description = 'black' 
    where c_id = 3; 

對於#3,ITEM_TOTAL> 2.什麼是這個項目總的基礎。你有

declare total int ; 
select total = item_total 
    from order_status; 

這不應該做任何事情,因爲它正在經歷每一個訂單,將只返回 1(真)或0(假)對每條記錄。您沒有任何標準,例如每個客戶的總數爲 ,甚至只是給定客戶的訂單數量...例如人員「A」有5個訂單, 和個人「B」有1個,人員「C」有你需要澄清你的意圖。 這提出了你的if/else的後續基於item_total> 2.選擇版本(a)或(b) 又一個查詢(不會複製/粘貼,因爲你不知道你的意圖)

在你的if(total> 2)else條件中,你的update語句沒有WHERE子句, ,所以它會更新order_status表中的每條記錄(可能不是你想要的)。

因此,稍微澄清一點,也許我自己和其他人可以提供一些樣本數據。
即使作爲一個新手,如果有東西可能是保密的,否則,你總是可以掩蓋 的事情,只顯示關鍵部分,但並不實際顯示生產數據,但顯示 示例數據,以幫助我們按照您的需求。現在和未來。

+0

感謝您的回答。幫助我很多。其實我是一名學生,所以我想不會有任何機密問題。 – user4053201 2014-09-19 02:26:37