MySql的複雜查詢

來源:互聯網
上載者:User

標籤:end   ros   name   send   mysql   username   sql   use   rom   

案例一:

有表message和user。

表message
messageid senderid recipientid content
1 1 2 "xxx"
2 2 3 "yyy"
3 1 3 "123"

表user
userid username
1 "Tom"
2 "Jim"
3 "Rose"

希望查詢的結果如下:
id sender recipient content
1 "Tom" "Jim" "xxx"
2 "Jim" "Rose" "yyy"
3 "Tom" "Rose" "123"

MySql的查詢語句如下:
SELECT s.messageid,s.username as "sender",b.username as "recipient"
FROM message a
INNER JOIN user b
ON b.userid=a.recipientid
RIGHT JOIN
(
SELECT a.messageid,b.username
FROM message a
INNER JOIN user b
ON b.userid=a.senderid
) s
ON s.messageid=a.messageid

案例二:

有表devicerecord和user。

表devicerecord
recordid device1 device2 device3 usetime
1 3 1 2 "2017-04-10 00:00:00"
2 2 1 3 "2017-04-11 01:00:00"
3 3 3 2 "2017-04-11 02:30:00"

表user
同上。

希望查詢的結果如下:
1 “Rose" "Tom" "Jim" "2017-04-10 00:00:00"
2 "Jim" "Tom" "Rose" "2017-04-11 01:00:00"
3 "Rose" "Rose" "Jim" "2017-04-11 02:30:00"

MySql的查詢語句如下:
SELECT m.recordid,col1.realname as "c1",col2.realname "c2",col3.realname as "c3",userdate
FROM deviceuserecord m
INNER JOIN user AS col1 ON m.device1=col1.userid
INNER JOIN user AS col2 ON m.device2=col2.userid
INNER JOIN user AS col3 ON m.device3=col3.userid

MySql的複雜查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.