具有连接数和案例数的Mysql查询 - 添加更多连接和子查询

时间:2013-11-02 11:02:35

标签: mysql sql

到目前为止,我已经得到了这个:

SELECT connections.id,
       connections.word_id,
       connections.order_id,
       connections.top,
       connections.deleted,
       (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(connections.modified)) AS modified_ago,
       words_en.word,
       (CASE WHEN words_en.user_id = 1 THEN "You" ELSE words_en.user_id END) AS created_by
FROM connections, words_en
WHERE connections.word_id = words_en.id AND connections.user_id = 1
ORDER BY connections.order_id

我想添加一些内容,但我无法正确使用语法。

  1. (CASE WHEN words_en.user_id = 1 THEN "You" ELSE words_en.user_id END)这里,当ELSE,而不是ID我想从users表中获取此用户的name_surname列。所以我需要再做一次加入?但既然是在这种情况下,我该怎么办呢?

  2. 来自SELECT的
  3. connections.word_id。除了ID,我还想知道连接表中这个word_id有多少次。但是从列表中排除当前用户。

  4. 我希望解释清楚。

2 个答案:

答案 0 :(得分:0)

SELECT connections.id,
       connections.word_id,
       connections.order_id,
       connections.top,
       connections.deleted,
       (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(connections.modified)) AS modified_ago,
       words_en.word,
       (CASE WHEN words_en.user_id = 1 THEN "You" ELSE users.name_surname END) AS created_by
FROM connections JOIN words
WHERE connections.word_id = words_en.id AND connections.user_id = 1 JOIN users ON users.id=words_en.user_id
ORDER BY connections.order_id

我无法从你的回答中告诉我如何链接用户表,发布表格模式。只是一个疯狂的猜测。

答案 1 :(得分:0)

首先,使用ANSI连接重写您的查询,并添加表别名,如下所示:

SELECT c.id,
       c.word_id,
       c.order_id,
       c.top,
       c.deleted,
       (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(c.modified)) AS modified_ago,
       words_en.word,
       (CASE WHEN words_en.user_id = 1 THEN "You" ELSE w.user_id END) AS created_by
FROM connections c
JOIN words_en w ON c.word_id = w.id
WHERE c.user_id = 1
ORDER BY c.order_id

现在扩展此查询变得更加容易:通过w.user_id引入用户,添加另一个加入:

SELECT c.id,
       c.word_id,
       c.order_id,
       c.top,
       c.deleted,
       (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(c.modified)) AS modified_ago,
       words_en.word,
       (CASE WHEN words_en.user_id = 1 THEN "You" ELSE u. name_surname END) AS created_by
FROM connections c
JOIN words_en w ON c.word_id = w.id
JOIN users u ON w.user_id = u.id
WHERE c.user_id = 1
ORDER BY c.order_id

要添加计数,请使用子查询,如下所示:

SELECT c.id,
       c.word_id,
       c.order_id,
       c.top,
       c.deleted,
       (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(c.modified)) AS modified_ago,
       words_en.word,
       (CASE WHEN words_en.user_id = 1 THEN "You" ELSE u. name_surname END) AS created_by,
       (
           SELECT COUNT(*)
           FROM connections cc
           WHERE cc.word_id=c.word_id     -- It's the same word
             AND cc.user_id <> c.user_id  -- user by a different user
       ) as uses_by_others
FROM connections c
JOIN words_en w ON c.word_id = w.id
JOIN users u ON w.user_id = u.id
WHERE c.user_id = 1
ORDER BY c.order_id