sql語句使用

2021-10-14 02:47:41 字數 2263 閱讀 3919

1.需求:按照查詢順序條件的排列順序返回

要點:where......in

select * from t_device where guid in ('guid1','guid2') order by field(guid,'guid1','guid2')
2.需求:替換資料表中的字段中相同資料

要點:replace函式

語法:replace(object,search,replace)

語義:把object物件**現的的search全部替換成replace。

update t_device set 'dev_code' = replace('dev_code','oldstr','newstr')
3.需求:實現有條件的聯合查詢

要點:條件約束的位置

正確例子:【在聯合查詢之後做整體條件約束】

select 

t_user.user_owner as first_id,

t_user_1.user_name as first_name,

v_cash_record.uid as second_id,

v_cash_record.user_name as second_name,

v_cash_record.* from v_cash_record

left join t_user on t_user.uid=v_cash_record.uid

left join t_user as t_user_1 on t_user_1.uid=t_user.user_owner

where v_cash_record.rid=3

錯誤的例子:注意【v_cash_record.rid=3】位置

select 

t_user.user_owner as first_id,

t_user_1.user_name as first_name,

v_cash_record.uid as second_id,

v_cash_record.user_name as second_name,

v_cash_record.* from v_cash_record

left join t_user on (t_user.uid=v_cash_record.uid and v_cash_record.rid=3)

left join t_user as t_user_1 on t_user_1.uid=t_user.user_owner

錯誤原因是:(t_user.uid=v_cash_record.uid and v_cash_record.rid=3) 恒為true,整體條件表示式的真值取決於and前面的條件【t_user.uid=v_cash_record.uid】,恒為真;and後面的條件【v_cash_record.rid=3】只是陪跑,並不影響整體表示式的值。

結論:聯合查詢時,不管是外聯,左聯,右聯,on後面都只能跟著乙個條件。

另一種正確寫法的例子:【在mysql資料庫中實測,低版本建立檢視時可能會報錯】

select 

t_user.user_owner as first_id,

t_user_1.user_name as first_name,

v_cash_record_1.uid as second_id,

v_cash_record_1.user_name as second_name,

v_cash_record_1.* from (select * from v_cash_record where rid=3) as v_cash_record_1

left join t_user on t_user.uid=v_cash_record_1.uid

left join t_user as t_user_1 on t_user_1.uid=t_user.user_owner

4.需求:將字段數量不同的兩張表(t_table1,t_table2)連線,其中 t_table1 字段包含 t_table2 的字段

要點:union,lack_col_1和lack_col_2為t_table1獨有字段。

select * from t_table1 union select *,null as lack_col_1,null as lack_col_2 from t_table2

SQL語句使用須知

1 說明 複製表 只複製結構,源表名 a 新錶名 b access可用 法一 select into b from a where 1 1 僅用於sqlserver 法二 select top 0 into b from a 2 說明 拷貝表 拷貝資料,源表名 a 目標表名 b access可用 i...

ACCESS中使用SQL語句

以下sql語句在access xp的查詢中測試通過 建表 create table tab1 id counter,name string,age integer,date datetime 技巧 自增字段用 counter 宣告.欄位名為關鍵字的字段用方括號括起來,數字作為欄位名也可行.建立索引 ...

基本的Sql語句使用

這篇文章就是記錄一下我學習sql語句的過程,會一直更新到我學習完資料庫的基本語句使用。對於安裝可以參照上篇文章 資料庫的安裝 我自己習慣centos下的mysql和ubuntu下的mysql。這學期開的課程,老師要求安裝windows下的sql server。正式開始記錄學習。已經學了一些了,之前沒...