MYSQL子查询,带有来自多表查询的过滤结果

时间:2014-12-18 21:38:20

标签: mysql database subquery

我正在尝试创建一个基于以下内容返回结果的查询:

该脚本现在适用于我,但我需要执行额外的步骤。我需要弄清楚如何筛选出任何' activity.dest_id'的结果。尚未在' user_requests'中确认表格并仅将其应用于' IN'中的最后一个值。在示例中,值将是'比尔'所有其他价值观,如时尚,艺术,建筑和#39;不必对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 
+------------+-----------+---------+------------+-----------+---------+-------------+

1 个答案:

答案 0 :(得分: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'

这可能不是最有效的方法,它也是未经测试的,但它对您的查询来说似乎是最符合逻辑的。