MYSQL 与多个 JOIN 联合

发布于 2024-12-11 16:15:51 字数 485 浏览 0 评论 0原文

我正在尝试编写一个查询来从具有相同列的 2 个 (list1,list2) 表中获取列表。 还有其他方法可以重写这段代码吗?

(SELECT r.id as rid, s.title, u.username  
FROM list1 r 
JOIN drama s ON r.parent_id = s.id 
LEFT JOIN image i ON s.image_id = i.id 
LEFT JOIN user u ON r.user_id = u.user_id) 

UNION ALL 

(SELECT r.id as rid, s.title, u.username  
FROM list2 r 
JOIN movie s ON r.parent_id = s.id 
LEFT JOIN image i ON s.image_id = i.id 
LEFT JOIN user u ON r.user_id = u.user_id) 
ORDER BY rid LIMIT 10

I'm trying to write a query to fetch a listing from 2 (list1,list2)tables with the same columns.
Are there any other way to rewrite this code?

(SELECT r.id as rid, s.title, u.username  
FROM list1 r 
JOIN drama s ON r.parent_id = s.id 
LEFT JOIN image i ON s.image_id = i.id 
LEFT JOIN user u ON r.user_id = u.user_id) 

UNION ALL 

(SELECT r.id as rid, s.title, u.username  
FROM list2 r 
JOIN movie s ON r.parent_id = s.id 
LEFT JOIN image i ON s.image_id = i.id 
LEFT JOIN user u ON r.user_id = u.user_id) 
ORDER BY rid LIMIT 10

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

司马昭之心 2024-12-18 16:15:51

如果你这样做有什么问题

SELECT r.id as rid, m.title AS movie Title, 
       d.title as DramaTitle, u.username  
FROM list1 r 
INNER JOIN movie m ON r.parent_id = m.id 
INNER JOIN drama d ON r.parent_id = d.id 
LEFT JOIN image i ON s.image_id = i.id 
LEFT JOIN user u ON r.user_id = u.user_id
ORDER BY r.id LIMIT 10 

whats wrong if you do this

SELECT r.id as rid, m.title AS movie Title, 
       d.title as DramaTitle, u.username  
FROM list1 r 
INNER JOIN movie m ON r.parent_id = m.id 
INNER JOIN drama d ON r.parent_id = d.id 
LEFT JOIN image i ON s.image_id = i.id 
LEFT JOIN user u ON r.user_id = u.user_id
ORDER BY r.id LIMIT 10 
溺深海 2024-12-18 16:15:51
SELECT r.id as rid, s.title, u.username  
FROM (SELECT l1.id, l1.user_id, l1.parent_id FROM list1 l1 
      UNION ALL 
      SELECT l2.id, l2.user_id, l2.parent_id FROM list2 l2) r
INNER JOIN drama s ON r.parent_id = s.id 
LEFT JOIN image i ON s.image_id = i.id 
LEFT JOIN user u ON r.user_id = u.user_id 
ORDER BY rid 
LIMIT 10
SELECT r.id as rid, s.title, u.username  
FROM (SELECT l1.id, l1.user_id, l1.parent_id FROM list1 l1 
      UNION ALL 
      SELECT l2.id, l2.user_id, l2.parent_id FROM list2 l2) r
INNER JOIN drama s ON r.parent_id = s.id 
LEFT JOIN image i ON s.image_id = i.id 
LEFT JOIN user u ON r.user_id = u.user_id 
ORDER BY rid 
LIMIT 10
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文