sql子查詢,多重查詢,join,左鏈接,右鏈接,內鏈接

範圍內重複數量查詢sql

根據上表查詢 每一個手機號都各有多少個重複的設備id優化

SELECT t.phone_num,COUNT(*) FROM 
(select phone_num, device_id,count(id) from d1_login_log group by phone_num,device_id ) as t 
GROUP BY t.phone_num;

通過前輩指導,優化了一下上面代碼,而且在推薦一本《SQL必知必會》一本書code

SELECT phone_num,count(distinct device_id) num from d1_login_log GROUP BY phone_num

-----------下面是子查詢相關內容-------------it

這裏子查詢替代了order的做用。固然,實際上不必這麼作,效率低。(子查詢當主查詢的條件)event

SELECT * FROM xxl_event2017 WHERE addtime = (SELECT MAX(addtime) FROM xxl_event2017)

查詢數據多於2條的分類,獲取該分類的id,再次使用該id查詢全部數據。若有命令不清楚可查閱我另外博文有詳細介紹。class

SELECT typeid,COUNT(*) as num FROM xxl_event2017 GROUP BY typeid HAVING num>2
SELECT typeid FROM (SELECT typeid,COUNT(*) as num FROM xxl_event2017 GROUP BY typeid HAVING num>2) as t
SELECT id,contacts,tel,typeid FROM xxl_event2017 WHERE typeid IN (SELECT typeid FROM (SELECT typeid,COUNT(*) as num FROM xxl_event2017 GROUP BY typeid HAVING num>2) as t)

第一條查詢結果:效率

第二條查詢結果:select

第三條查詢結果:im

左鏈接:注意field部分重疊處須要點名是哪一個表的。數據

SELECT a.itemid,title,content FROM xxl_sell_5 a 
LEFT JOIN xxl_sell_data_5 b ON a.itemid = b.itemid WHERE typeid=0

以下圖,itemid存在於a,b表中,使用itemid綁定來查詢對應的b表的content。右鏈接同理。

INNER JOIN,內鏈接。

內鏈接僅有交集的數據。如itemid在a表有1,2,3,4。b表有3,4,5,6查詢時僅會出現3,4的內容。

自行嘗試,就不提供例子了。。

以爲有用求給個贊 - -

相關文章
相關標籤/搜索