1 常用Sql查詢
表A和表B要做關聯查詢:
表A當成主查詢表:查詢記錄主體從主查詢表出
表B關聯表
1.1 內鏈接關聯查詢:
如果表A和表B有一個外鍵關聯 ,可以通過外鍵進行內鏈接查詢
select dictinfo.*,dicttype.typename
from dictinfo, dicttype
where dictinfo.typecode = dicttype.typecode
--不通過外鍵,通過groupid查詢用戶類型的代碼結果集,只能查詢出一條記錄,可以使用內鏈接
selectsysuser.*, dictinfo.info
from sysuser,
(select dictcode, typecode, infofrom dictinfo where typecode = 's01') dictinfo
where sysuser.groupid = dictinfo.dictcode
小結:如果主查詢表字段從關聯表只查詢出一條記錄,這個字段就可以作爲內鏈接關聯字段
--內鏈接的錯誤的例子,通過關聯查詢出重複記錄
--使用groupid從select dictcode, typecode, info fromdictinfo可以找到多個記錄,不能使用內鏈接,可能會出現重複記錄
selectsysuser.*
from sysuser, (select dictcode, typecode, infofrom dictinfo) dictinfo
where sysuser.groupid = dictinfo.dictcode
注意:如果使用內鏈接查詢出現重複記錄,首先去思考是否是sql寫錯了,不能直接去使用distinct去除重複記錄。
有一些特殊情況下還是需要使用distinct去除重複記錄,比如複雜的統計分析sql。
1.2 外鏈接關聯查詢:
表A,表B中只有一部分數據和表A匹配,不能使用內鏈接。
主查詢是表A,只能使用外鏈接。
--查詢用戶所屬單位,sysid對應三張表的id
selectsysuser.*,useryy.mcfrom sysuser leftjoin useryyon sysuser.sysid =useryy.id
select *from useryy rightjoin sysuseron sysuser.sysid =useryy.id
--以上的需要不能使用內鏈接
selectsysuser.*,useryy.mcfrom sysuser,useryywhere sysuser.sysid = useryy.id
小結:
表A中從表B中只能關聯查詢一部分數據,只能使用外鏈接
1.3 子查詢
selectsysuser.*,
(select * from useryywhereid = sysuser.sysid)
from sysuser
子查詢只能返回一列,否則:報值過多
子查詢只允許返回一行,否則:返回一行對應多行
正確的sql:
--子查詢
--根據sysid取出單位名稱
--根據groupid查詢用戶類型代碼對應的名稱
selectsysuser.*,
(select mcfrom useryy whereid = sysuser.sysid)sysmc,
(select infofrom dictinfo where dictcode = sysuser.groupidand typecode = 's01')groupname
from sysuser
1.4 嵌套表
可以將一個sql查詢結果組成一個虛表,查詢方式和查詢一個實體表相同的。
組成的虛擬表字段是不允許重複的,否則:未明確定義列