我有2个数据库db1
和db2
-
db1
-movies
和tickets
中有2个表。
db2
-boxoffice
中有1个表。
我想在获取结果时应用以下逻辑-
if boxoffice.movie_id == movie.id
tickets.movie_id = boxoffice.movie_id
else
tickets.movie_id = movie.id
end
我写了这样的东西,但是不完整-
select mvoie_id from tickets-- query that i was using...some syntax might be wrong but this is to give you the idea of what i was trying to do
(select case
when db2.boxoffice.movie_id = db1.movie.id then db1.tickets.movie_id= db2.boxoffice.movie_id
else db1.tickets.movie_id = db1.movie.id end)
预期结果-
Tickets table
id movie_id
由于我无法构建查询,有人可以帮助查询吗?
答案 0 :(得分:1)
SELECT tickets.* (
SELECT (
CASE
WHEN movies.id IS NOT NULL THEN boxoffice.movie_id
ELSE movies.id
END
) AS movie_id
FROM movies
LEFT JOIN boxoffice ON boxoffice.movie_id = movies.id
) AS data_table
JOIN tickets ON tickets.movie_id = data_table.movie_id
说明:
WHEN movies.id IS NOT NULL THEN boxoffice.movie_id
,检查是否存在与条件if if boxoffice.movie_id == movie.id
类似的匹配,否则,忽略这些行并仅考虑movie.id
答案 1 :(得分:0)
如果我理解正确,可以尝试一下。
SELECT t2.*
FROM (
SELECT b.movie_id
FROM boxoffice b JOIN movie m
ON b.movie_id = m.id
UNION ALL
SELECT m.id
FROM boxoffice b JOIN movie m
ON b.movie_id <> m.id
) t1 JOIN tickets t2 ON t1.movie_id = t2.movie_id
或者您可以尝试在郊区使用LEFT JOIN
SELECT t2.*
FROM (
SELECT (CASE WHEN m.id IS NOT NULL THEN b.movie_id ELSE m.id END) movie_id
FROM boxoffice b LEFT JOIN movie m
ON b.movie_id = m.id
) t1 JOIN tickets t2 ON t1.movie_id = t2.movie_id