我有2个数据库db1db2-

db1-moviestickets中有2个表。
db2-boxoffice中有1个表。

我想在获取结果时应用以下逻辑-

if boxoffice.movie_id == movie.id
  tickets.movie_id = boxoffice.movie_id
else
  tickets.movie_id = movie.id
end


mysql - SQL case语句-根据其他2个表从第三个值中选择值-LMLPHP
考虑票证表类似于这些

我写了这样的东西,但不完整-

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

我无法构建查询,有人可以提供帮助吗?

最佳答案

如果我理解正确,可以尝试一下。

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


或者您可以尝试在subuqery中使用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

关于mysql - SQL case语句-根据其他2个表从第三个值中选择值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57026080/

10-11 08:23