mysql動態sql無效 sql動態列的問題?

2021-10-18 22:03:06 字數 1509 閱讀 6362

一種效率並不高的方案, 我想想看有沒有更加高效的方法, 想到後在來編輯

create table ttd(

pname varchar(30),

pcode int,

cname varchar(30),

ccode int,

yname varchar(30),

ycode int

insert into ttd(pname, pcode, cname, ccode, yname, ycode) values

('北京', 110000, '北京', 110000,'東城', 110101),

('天津',120000, '天津', 120000, '和平', 120101),

('河北', 130000, '石家莊', 130100, '長安', 130102),

('河北', 130000, '唐山', 130200, '路南', 130202),

('河北', 130000, '秦皇島', 130300, '海港', 130302),

('河北', 130000, '邯鄲', 130400, '復興', 130404);

select pname, pcode, yname, ycode from ttd where pname in ('北京', '天津')

union

select pname, pcode, cname, ccode from ttd where pname not in ('北京', '天津')

相對來說這種方案效率會高於上方的方式

select pname, pcode,

case pname

when '北京' then yname

when '天津' then yname

else cname

end as cname,

case pname

when '北京' then ycode

when '天津' then ycode

else ccode

end as ccode

from ttd

如果是 mysql 的話還可以這麼玩, 在 postgresql 中怎麼試都不過..

select pname, pcode, if(cname=pname, yname, cname) as cname, if (cname=pname, ycode, ccode) as ccode from ttd

還有個思路是 如果 cname=pname 就替換成 null 然後用 isnull 判斷是取 yname 或者 cname , 當然這種方案並不靠譜, replace 函式貌似不支援替換乙個欄位...

當然啦, 這倆放方案的前提是你的 北京和天津 的 cname 要和 pname 一樣,才可以用

我只是有點無聊. 其實實現這個功能的方案還有很多種, 在比如你單獨返回乙個 cname=pname as b 這樣你在程式裡面取 b ? yname : cname 當然也要和剛剛說的一樣 cname 和 pname 相同

我得走人了 .

mysql動態sql無效 mysql 動態sql

解析類 xmllanguagedriver 可以通過setting 中的配置解析類。xmlscriptbuilder 動態sql 語句 bind bindhandler and 通過ognl 計算值,賦值給變數 foreachhandler forecah 標籤的解析解析 select from b...

mybatis動態sql排序無效問題

在使用mybatis解析xml進行排序的時候,遇見排序無效的問題!將傳入的資料都當成乙個字串,會對自動傳入的資料加乙個雙引號。如 order by 如果傳入的值是111,那麼解析成sql時的值為order by 111 如果傳入的值是id,則解析成的sql為order by id 將傳入的資料直接顯...

mysql動態sql語句

直接執行sql宣告 sqlstatement 例程 string mysql mysql create table employee emp id integer not null,dept id integer not null,emp fname char 10 not null,emp lna...