我正试图用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;
然而,我收到一个错误。这有什么问题,还有更好的方法吗?
答案 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;