-5

一共有三个表请看这个结构

用户表

====================== 

id(users.id) |username | status
----------------------------------
56           | mark     | 1
----------------------------------
57           | john     | 1
----------------------------------
58           | lina     | 1
----------------------------------
59           | lara     | 1
----------------------------------

眨眼表

======================  
wink_id | from_id(fk from users.id) | to_id(fk from user.id) | wink_flag
--------------------------------------------------------------------------
1       | 56                        | 57                     | 1
--------------------------------------------------------------------------
2       | 56                        | 58                     | 1
--------------------------------------------------------------------------

最喜欢的桌子

====================== 
fav_id  | from_id(fk from user.id)  | to_id(fk from user.id) | fav_flag 
------------------------------------------------------------------------
1       | 56                        | 59                      | 1
------------------------------------------------------------------------
1       | 56                        | 58                      | 1
------------------------------------------------------------------------

想离开加入有这样的数据。

=======================================================================


id  |  wink_flag  |  fav_flg | status
------------------------------------
57  |  1          | Null
------------------------------------
58  |  1          | 1
------------------------------------
59  |  Null       | 1
------------------------------------

我正在使用左连接与用户加入这两个表眨眼和收藏

  1. 询问

当结果出现时 user.id <> 56

表示当我使用 56 user.id 登录时

然后我将让除我之外的所有用户行认为我以 56 user.id 身份登录

结果将如下所示。

======================================
id  |  wink_flag  |  fav_flg | status
------------------------------------
57  |  1          | Null
------------------------------------
58  |  1          | 1
------------------------------------
59  |  Null       | 1
------------------------------------

我怎样才能编写 sql 查询以获得上述结果。

帮我。

4

2 回答 2

0

You should try LEFT JOIN

   SELECT u.id, w.wink_flag, f.fav_flag, u.status
     FROM users u
LEFT JOIN winks w 
          ON u.id = w.to_id
LEFT JOIN favourite f 
          ON u.id = f.to_id
    WHERE w.wink_flag IS NOT NULL 
       OR f.fav_flag IS NOT NULL;

Result:

╔════╦═══════════╦══════════╦════════╗
║ ID ║ WINK_FLAG ║ FAV_FLAG ║ STATUS ║
╠════╬═══════════╬══════════╬════════╣
║ 57 ║ 1         ║ (null)   ║      1 ║
║ 58 ║ 1         ║ 1        ║      1 ║
║ 59 ║ (null)    ║ 1        ║      1 ║
╚════╩═══════════╩══════════╩════════╝

See this SQLFiddle

于 2013-05-13T08:01:05.733 回答
-1

LEFT JOIN看演示SQL Fiddle

SELECT
  u.id,
  (SELECT
     w.wink_flag
   FROM winks w
   WHERE w.to_id = u.id
   GROUP BY w.to_id) AS WINK_FLAG,
  (SELECT
     f.fav_flag
   FROM favourite  f
   WHERE f.to_id = u.id
   GROUP BY f.to_id) AS FAV_FLAG

FROM users u
WHERE u.id != 56
于 2013-05-13T08:29:49.720 回答