2014-12-18 555 views
1

我试图创建一个返回基于以下结果的查询过滤结果:MYSQL子查询与多表查询

的脚本对我的作品,但现在我需要执行额外的步骤。我需要弄清楚如何过滤掉'user_requests'表中尚未确认的任何'activity.dest_id'的结果,并将其仅应用于'IN'中的最后一个值。在这个例子中,值为'Bill',所有其他值(如'Fashion,Art,Architecture')都不需要针对user_requests表进行检查,因为这些值不是人物。谢谢您的帮助。

 
SELECT a.activity_type, a.dest_id, o.opinion_id, o.fromUser, o.image_data, o.votedYes, o.votedNo, o.created_at, o.expires_at 
FROM activity a, opinions o 
WHERE a.opinion_id = o.opinion_id 
AND NOT 
EXISTS (
SELECT opinion_id, fromUser 
FROM user_activity u 
WHERE u.opinion_id = a.opinion_id 
) 
AND a.dest_id 
IN (
"Fashion", "Art", "Architecture", "Bill" 
) 
 user_activity table 
+------------+-----------+ 
| opinion_id | fromuser 
------------+-----------+ 
| 9   | Jim 
| 10   | Sam 
+------------+-----------+ 
 user_requests table 
+------------+-----------+---------+ 
| fromUser | toUser | type | status 
------------+-----------+----------+ 
| Ana  | Bill | C | 1 
| Kate  | Bill | P | 0 
+------------+-----------+---------+ 
 activity table 
+------------+-------+ 
| fromUser | dest_id 
------------+--------+ 
| Ana  | Fashion 
| Ana  | Art 
| Kate  | Bill 
| Tom  | Fashion 
| Bill  | Fashion 
| Kim  | Art 
| Kim  | Art 
| Ana  | Fashion 
| Kim  | Ana 
+------------+-------+ 
 opinion table 
+------------+-----------+---------+------------+-----------+---------+--------------+ 
| opinion_id | fromUser | image_data | votedYes | votedNo | created_at | expires_at 
+------------+-----------+---------+------------+-----------+---------+--------------+ 
| 1   | Ana  | non  | 1  | 3  | 2014-12-17 | 2014-12-18 
| 2   | Ana  | non  | 1  | 3  | 2014-12-17 | 2014-12-18 
| 3   | Ana  | non  | 1  | 3  | 2014-12-17 | 2014-12-18 
| 4   | Ana  | non  | 1  | 3  | 2014-12-17 | 2014-12-18 
| 5   | Ana  | non  | 1  | 3  | 2014-12-17 | 2014-12-18 
+------------+-----------+---------+------------+-----------+---------+-------------+ 

回答

0

它看起来像你需要一个连接。 我假设您需要将user_activity表中的fromuser与user_requests表中的fromuser联合起来。

不P =待定 和C =确认

如果这是正确的,

SELECT * FROM (
SELECT a.activity_type, a.dest_id, o.opinion_id, o.fromUser, o.image_data, o.votedYes, o.votedNo, o.created_at, o.expires_at 
FROM activity a, opinions o 
WHERE a.opinion_id = o.opinion_id 
AND NOT 
EXISTS (
SELECT opinion_id, fromUser 
FROM user_activity u 
WHERE u.opinion_id = a.opinion_id 
) 
AND a.dest_id 
IN (
"Fashion", "Art", "Architecture", "Bill" 
) 
) x INNER JOIN user_requests ON x.fromUser = user_requests.fromUser 
WHERE user_requests.type = 'C' 

这可能不是最好的有效的方式做到这一点,这也是未经测试,但它似乎与您的查询最符合逻辑。