根据列值选择另一行

时间:2010-11-10 15:45:26

标签: mysql

如果我在下面的查询中选择了一个论坛板,但board表包含一列mirror_board_id。我是否可以将基本选择查询修改为mirror_board_id > 0 SELECT * FROM board WHERE board_id = mirror_board_idSELECT * FROM board WHERE category_id = 7 AND board_id = 0 的位置。目前我正在使用2个查询来完成此任务,但这有点查询密集......

SELECT * FROM board WHERE category_id = 7 AND
                            (
                                    (
                                        mirror_board_id > 0
                                        AND board_id = mirror_board_id
                                    )
                                OR board_id = 0
                            ) AND
                            display = 1 ORDER BY `order` ASC

更新

mirror_board_id > 0

这是在列表中返回错误的板,它实际上并没有返回镜板,而是原来的板{{1}}

1 个答案:

答案 0 :(得分:4)

逻辑上,它是:

SELECT * 
FROM board 
WHERE (mirror_board_id > 0 and board_id = mirror_board_id) 
    or board_id = 0 

这可以更简洁地写成:

SELECT * 
FROM board 
WHERE board_id = coalesce(mirror_board_id, 0)