我有两张桌子
tbl_cid
-------------------------
| cid | sid | rid | dt |
-------------------------
| 1 | 101 | 103 | xxx |
| 6 | 104 | 101 | xxx |
| 8 | 104 | 103 | xxx |
| 9 | 105 | 104 | xxx |
-------------------------
tbl_uid
--------------
| uid | name |
--------------
| 101 | john |
| 103 | tim |
| 104 | paul |
| 105 | alex |
--------------
SELECT u.name, c.cid, c.sid, c.rid FROM tbl_cid c
JOIN tbl_uid u on u.uid = c.sid
WHERE c.sid = 101 OR c.rid = 101
Expected result:
--------------------
| cid | uid | name |
--------------------
| 1 | 103 | tim |
| 6 | 104 | paul |
--------------------
我以不同的方式尝试过,但无法找到它。
假设我在tbl_cid
中搜索101,如果sid有101则加入rid,如果rid有101则加入sid。任何帮助是极大的赞赏。谢谢
答案 0 :(得分:0)
我认为这就是你要找的东西:
select tbl_cid.cid, tbl_uid.uid, tbl_uid.name
from tbl_cid, tbl_uid
where (tbl_cid.sid = tbl_uid.uid AND tbl_cid.rid = 101) OR (tbl_cid.rid = tbl_uid.uid AND tbl_cid.sid = 101);
Result:
--------------------
| cid | uid | name |
--------------------
| 1 | 103 | tim |
| 6 | 104 | paul |
--------------------
答案 1 :(得分:0)
我实际上不同意@wdika,你应该使用连接,因为使用带有两个表的where子句只是隐式地进行连接。
SELECT u.name, c.cid, c.sid, c.rid FROM tbl_cid c
JOIN tbl_uid u on u.uid = c.sid or u.uid = c.rid
WHERE (c.sid = 101 OR c.rid = 101) and u.uid != 101;