在mysql中组合两个表

时间:2012-08-01 15:41:57

标签: mysql sql

我有三张桌子

   table name: tags
          id (int)
          tag_name (vharchar)    

   table name: messages
          id (int)
          message_title (vharchar)
          message_content(vharchar)

    table name: message_tag
          message_id (int)
          tag_id (int)

我已经尝试过这段代码,但它没有用(返回空)

SELECT messages.message_title, messages.message_content, tags.tag_name
            FROM messages
            INNER JOIN message_tag ON messages.id = message_tag.message_id
            INNER JOIN tags ON tags.id = message_tag.tag_id
            WHERE message_tag.tag_id =191
            AND message_tag.tag_id =19
            AND message_tag.tag_id =31
            ORDER BY RAND( )
            LIMIT 20

我想选择连接到标签191,19和31的随机20行

3 个答案:

答案 0 :(得分:5)

SELECT messages.message_title, messages.message_content, tags.tag_name
        FROM messages
        INNER JOIN message_tag ON messages.id = message_tag.message_id
        INNER JOIN tags ON tags.id = message_tag.tag_id
        WHERE message_tag.tag_id IN (191, 19, 31)
        ORDER BY RAND( )
        LIMIT 20

使用IN代替AND。这将为您带来至少与这些特定标签相关联的消息。

更新: IF 您想要获取所有3个标签都存在的消息,您可以这样做(假设您在message_tag中的行是唯一的):

    SELECT messages.message_title, messages.message_content, tags.tag_name
        FROM messages
        INNER JOIN message_tag ON messages.id = message_tag.message_id
        INNER JOIN tags ON tags.id = message_tag.tag_id
        WHERE message_tag.tag_id IN (191, 19, 31)
        GROUP BY messages.id
        HAVING COUNT(messages.id) > 2
        ORDER BY RAND( )
        LIMIT 20

答案 1 :(得分:3)

检索行,因为您的条件无效。它总是会导致falsetag_id只能有 1个可能的值,而不是很多。试试这个:

SELECT messages.message_title, messages.message_content, tags.tag_name
FROM messages
         INNER JOIN message_tag 
              ON messages.id = message_tag.message_id
         INNER JOIN tags 
              ON tags.id = message_tag.tag_id
WHERE message_tag.tag_id IN (191, 19, 31)
ORDER BY RAND( )
LIMIT 20

使用IN子句代替AND

更新1

SELECT messages.message_title, messages.message_content, tags.tag_name
FROM messages
         INNER JOIN message_tag 
              ON messages.id = message_tag.message_id
         INNER JOIN tags 
              ON tags.id = message_tag.tag_id
WHERE message_tag.tag_id IN (191, 19, 31)
GROUP BY messages.message_title
HAVING COUNT(*) = 3
ORDER BY RAND( )
LIMIT 20

答案 2 :(得分:1)

条件message_tag.tag_id =191 AND message_tag.tag_id =19 AND message_tag.tag_id =31表示不相交集的交集,因此它表示空集。

你需要这套的联合。只需将AND替换为OR