資料庫操作常用的查詢方法

2021-08-14 09:19:55 字數 2193 閱讀 1570

如果表a和表b有乙個外來鍵關聯 ,可以通過外來鍵進行內鏈結查詢

select dictinfo.*, dicttype.typename

from dictinfo, dicttype

where dictinfo.typecode = dicttype.typecode

--不通過外來鍵,通過groupid查詢 使用者型別的**結果集,只能查詢出一條記錄,可以使用內鏈結

select sysuser.*, dictinfo.info

from sysuser,

(select dictcode, typecode, info from dictinfo where typecode = 's01') dictinfo

where sysuser.groupid = dictinfo.dictcode

--內鏈結的錯誤的例子,通過關聯查詢出重覆記錄

--使用groupid從select dictcode, typecode, info from dictinfo可以找到多個記錄,不能使用內鏈結,可能會出現重覆記錄

select sysuser.*

from sysuser, (select dictcode, typecode, info from dictinfo) dictinfo

where sysuser.groupid = dictinfo.dictcode

有一些特殊情況下還是需要使用distinct去除重覆記錄,比如複雜的統計分析sql。

表a,表b中只有一部分資料和表a匹配,不能使用內鏈結。

主查詢是表a,只能使用外鏈結。

--查詢使用者所屬單位,sysid對應三張表的id

select sysuser.*,useryy.mc from sysuser left join useryy on sysuser.sysid = useryy.id

select * from useryy right join sysuser on sysuser.sysid = useryy.id

--以上的需要不能使用內鏈結

select sysuser.*,useryy.mc from sysuser, useryy where  sysuser.sysid = useryy.id
小結:

表a中從表b中只能關聯查詢一部分資料,只能使用外鏈結

⦁    子查詢

select sysuser.*,

(select * from useryy where id = sysuser.sysid)

from sysuser

子查詢只能返回一列,否則 :

子查詢只允許返回一行,否則 :

正確的sql:

--子查詢

--根據sysid取出單位名稱

--根據groupid查詢使用者型別**對應的名稱

select sysuser.*,

(select mc from useryy where id = sysuser.sysid)sysmc,

(select info from dictinfo where dictcode = sysuser.groupid and typecode = 's01')groupname

from sysuser

⦁    巢狀表

可以將乙個sql查詢結果組成乙個虛表,查詢方式和查詢乙個實體表相同的。

組成的虛擬表字段是不允許重複的,否則 :

mongoose 常用資料庫操作 查詢

條件查詢 model.find conditions,fields options callback demo1 try.js var user require user.js function getbyconditions user.find wherestr,function err,res ...

Sqlserver 資料庫 表常用查詢操作

查詢所有表以及記錄數 select a.name as 表名,max b.rows as 記錄條數 from sysobjects a sysindexes b where a.id b.id and a.xtype u group by a.name order by max b.rows des...

資料庫的查詢操作

1.1 建立表 create table tablename fieldname type constraints,1.2 記錄操作 1.2.1 增加 insert into tablename values 1 2 3 4 或者 insert into tablename 1 2 3 4 1.2....