我遇到了MySQL查询的问题(我是新手,所以对我来说很容易!)。我有一个有电视节目的网站,想要根据两个不同的动作(自定义时间表)选择两个日期之间播出的剧集(没问题)。基本上,如果用户要么关注(uses_follow_shows)或观看节目(user_watched),我想要显示剧集,所以我想我会有类似下面的东西,但这不起作用。除了我的结果在一侧有一个查询的结果而在另一侧有另一个查询结果的事实之外,它的工作正常。
即:
name a1 name a
Mistresses (US) 2 Wilfred (US) 2
Mistresses (US) 2 Dexter 2
这是我的疑问:
我怎样才能使我的所有名字都在同一栏?
SELECT * FROM (
SELECT shows.name, users_follow_shows.user_id a1
FROM show_episode_airdate join
show_episode
on show_episode.episode_id = show_episode_airdate.episode_id join
shows
on shows.imdb_id = show_episode.imdb_id_show join
show_network
on show_network.show_id = shows.id join
network
on show_network.network_id = network.network_id join
users_follow_shows
on shows.id = users_follow_shows.show_id
WHERE show_episode_airdate.airdate BETWEEN '2013-07-20' AND '2013-07-27' and
users_follow_shows.user_id = 2
ORDER by network.network_id ASC) a1
JOIN (
SELECT shows.name, user_watched.user_id a
FROM show_episode_airdate join
show_episode
on show_episode.episode_id = show_episode_airdate.episode_id join
shows
on shows.imdb_id = show_episode.imdb_id_show join
show_network
on show_network.show_id = shows.id join
network
on show_network.network_id = network.network_id join
user_watched
on shows.id = user_watched.show_id
WHERE show_episode_airdate.airdate BETWEEN '2013-07-20' AND '2013-07-27' and
user_watched.user_id = 2
ORDER by network.network_id ASC) a
ON a = a1
任何帮助表示赞赏。感谢。
答案 0 :(得分:3)
你不应该使用JOIN。您正在寻找的是UNION:
答案 1 :(得分:1)
你可以从这个子查询开始:
SELECT DISTINCT user_id, show_id
FROM (
SELECT user_id
show_id
FROM user_watched
UNION
SELECT user_id
show_id
FROM user_follows_show
)
这将为您提供一个独特用户的虚拟表格,并显示符合您的两个条件,以便将它们包含在列表中。然后,您可以将其加入查询的其余部分,如下所示:
SELECT whatever
FROM whatever
JOIN (
SELECT DISTINCT user_id, show_id
FROM (
SELECT user_id
show_id
FROM user_watched
UNION
SELECT user_id
show_id
FROM user_follows_show
) USER_INTERESTED ON USER_INTERESTED.show_id = shows.id
WHERE whatever
诀窍是使用结构化查询语言的结构化部分来获取查询请求所需的用户/节目之间的虚拟关系。
答案 2 :(得分:0)
未经测试但我会像这样简化您的查询:
SELECT
shows.name,
users_follow_shows.user_id a1
FROM show_episode_airdate
JOIN show_episode on show_episode.episode_id = show_episode_airdate.episode_id
JOIN shows on shows.imdb_id = show_episode.imdb_id_show
JOIN show_network on show_network.show_id = shows.id
JOIN network on show_network.network_id = network.network_id
LEFT JOIN users_follow_shows on shows.id = users_follow_shows.show_id
LEFT JOIN user_watched on shows.id = user_watched.show_id
WHERE show_episode_airdate.airdate BETWEEN '2013-07-20' AND '2013-07-27'
AND (users_follow_shows.user_id = 2 OR user_watched.user_id = 2)