我有三个表:pages,blocks和pages_blocks。
我的数据库架构如下所示:
CREATE TABLE `blocks` (
`id` smallint(6) NOT NULL AUTO_INCREMENT,
`name` char(40) NOT NULL,
`content` text NOT NULL
PRIMARY KEY (`id`)
);
CREATE TABLE `pages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` char(100) NOT NULL,
`content` mediumtext NOT NULL
PRIMARY KEY (`id`)
);
CREATE TABLE `pages_blocks` (
`page_id` int(11) DEFAULT NULL,
`block_id` smallint(6) DEFAULT NULL,
`location` enum('left','right') DEFAULT NULL,
`display_order` smallint(6) DEFAULT NULL
);
获取特定页面的“左”和“右”块的完美SQL代码是什么?
非常感谢您的帮助。
答案 0 :(得分:1)
一种方法是左右两个连接搜索:
select *
from pages p
left join
(
select *
from pages_blocks pb
join blocks b
on pb.block_id = b.id
where pb.location = 'left'
) left_block
on left_block.page_id = p.id
left join
(
select *
from pages_blocks pb
join blocks b
on pb.block_id = b.id
where pb.location = 'right'
) right_block
on right_block.page_id = p.id
where p.id = 42
这样做的好处是只返回一行而不使用group by
。
编辑:如果可以有多个“右”和“左”块,您可以查询所有块,如:
select pb.location
, pb.display_order
, b.name
, b.content
from pages p
join pages_blocks pb
on pb.page_id = p.id
join blocks b
on pb.block_id = b.id
where p.id = 42
order by
pb.location
, pb.display_order
答案 1 :(得分:1)
您可以使用UNION:
select a.content
from blocks a, pages_blocks b
where a.id=b.block_id and b.page_id=123 and b.location='left'
union
select a.content
from blocks a, pages_blocks b
where a.id=b.block_id and b.page_id=123 and b.location='right'