繁体   English   中英

内部连接与 3 个表(第二个和第三个“分配”给第一个 - 不是全部在一起)

[英]Inner join with 3 tables (the second and third "assigned" to the first - not all together)

我有 3 张桌子,我想“内部连接” -但总是到第一张桌子

SELECT *
FROM scene_block AS sb
INNER JOIN roles AS r ON (sb.selected_block = r.id 
                         AND sb.block_type = 'role' 
                         AND r.id NOT IN (21))
INNER JOIN script_actors AS sa ON (sb.selected_block = sa.id 
                                  AND sb.block_type = 'actor')
WHERE 
    sb.scene_id = '1'
GROUP BY
    sb.id
ORDER BY 
    sb.position

使用 LEFT JOIN 的相同查询返回所有结果,如预期的 r.id 21“NULL”,使用 INNER JOIN 的查询返回 0 个结果(因为所有内部连接在一起) Result Left Join但这不是我想要实现的。 ..

我想实现,如果在 scene_block "block_type='role'" 角色表将被内部连接,如果 block_type='actor' 脚本_actors 将被内部连接......并且行之间的链接总是scene_block.selected_id = .id

CREATE TABLE `scene_block` (
  `id` int(11) UNSIGNED NOT NULL,
  `scene_id` int(11) NOT NULL,
  `block_type` enum('actor','role') NOT NULL,
  `selected_block` int(11) DEFAULT NULL,
  `content` text NOT NULL,
  `hideable` enum('0','1') NOT NULL DEFAULT '1',
  `position` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `script_actors` (
  `id` int(11) NOT NULL,
  `script_id` int(11) NOT NULL,
  `realname` varchar(200) NOT NULL,
  `actorname` varchar(200) NOT NULL,
  `description` text NOT NULL,
  `position` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `roles` (
  `id` int(11) UNSIGNED NOT NULL,
  `location_id` int(11) NOT NULL,
  `title` varchar(256) NOT NULL,
  `color` varchar(7) NOT NULL,
  `color_live` varchar(7) NOT NULL,
  `position` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在没有对您的数据进行测试的情况下,我认为如果您使用INNER JOIN而不是LEFT JOIN ,您会更接近您想要的结果。

SELECT *
FROM scene_block AS sb
INNER JOIN roles AS r ON (sb.selected_block = r.id 
                     AND sb.block_type = 'role' 
                     AND r.id NOT IN (21))
INNER JOIN script_actors AS sa ON (sb.selected_block = sa.id 
                                   AND sb.block_type = 'actor')
WHERE 
sb.scene_id = '1'
GROUP BY
sb.id
ORDER BY 
sb.position

内部连接在这里不起作用,因为场景块类型不能同时是“角色”和“演员”。 您需要外部联接来获取角色或演员。 然后添加一个条件以去除不匹配的场景块。

SELECT *
FROM scene_block AS sb
LEFT JOIN roles AS r ON sb.selected_block = r.id 
                    AND sb.block_type = 'role' 
                    AND r.id <> 21
LEFT JOIN script_actors AS sa ON sb.selected_block = sa.id 
                             AND sb.block_type = 'actor'
WHERE sb.scene_id = 1
AND (sa.id IS NOT NULL OR r.id IS NOT NULL)
ORDER BY sb.position;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM