在自身内部使用自己的结果的SQL查询

时间:2015-01-04 15:35:11

标签: mysql database

我正试图用mysql编写这个查询,我将不胜感激。我有两张桌子:

files (id, name, subject, size, day, hour, username) and 
friendships (user1, user2). 

我想从表10 most recent中选择files行(就ID而言)username,其中每行friendships出现在表second column中, friendships的{​​{1}}等于某些name 'x'

我正在尝试使用此声明:

SELECT name, 
       subject, 
       size, 
       day, 
       hour, 
       username 
FROM   files 
WHERE  username IN ((SELECT user1 
                     FROM   friendships 
                     WHERE  user2 = 'x') 
                    UNION ALL 
                    (SELECT user2 
                     FROM   friendships 
                     WHERE  user1 = 'x')) 
ORDER  BY id DESC 
LIMIT  10;

然而,我收到一个错误。这有什么问题,还有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

我不确定是什么导致了您的错误,但有更好的方法。将其拆分为两个操作。我通常使用exists(虽然in可能很好):

WHERE EXISTS (SELECT 1 FROM friendships fs WHERE fs.user2 = 'x' and fs.user1 = files.username) OR
      EXISTS (SELECT 1 FROM friendships fs WHERE fs.user1 = 'x' and fs.user2 = files.username) 

此公式将允许查询更好地利用索引,尤其是friendships(user1, user2)friendships(user2, user1)(是的,在这种情况下,两者都是可取的)。

答案 1 :(得分:1)

尝试删除大括号。

SELECT name, 
       subject, 
       size, 
       day, 
       hour, 
       username 
FROM   files 
WHERE  username IN (SELECT user1 
                     FROM   friendships 
                     WHERE  user2 = 'x' 
                    UNION ALL 
                    SELECT user2 
                     FROM   friendships 
                     WHERE  user1 = 'x') 
ORDER  BY id DESC 
LIMIT  10;