如何简化sql语句

时间:2015-12-01 01:39:54

标签: mysql sql

我有以下查询 -

select * from main_iteminstance where master_id=33568
  or tv_series_id  in 
(select id from main_iteminstance where master_id=33568)

如何最好地简化?

基本上,我想要的是:

ids = select id from main_iteminstance where master_id=33568
child_ids = select id from main_iteminstance where tv_series_id in ids
my_answer = ids + child_ids

3 个答案:

答案 0 :(得分:1)

进一步查看后,子查询正在执行查找,其中master_id与父查询的值相同。这意味着tv_series_id的条件是多余的,因为它只会返回已在父级中找到的结果。

您最简单的结果集将是:

SELECT * 
FROM   main_iteminstance 
WHERE  master_id=33568

除非您正在寻找tv_series_id来匹配id where master_id != 33568

SQLFiddle

此示例演示了tv_series_id与master_id!= 33568的id匹配的位置。如果不需要,可以删除OR及其后的所有内容。

答案 1 :(得分:1)

另一种方法是将表连接起来:

SELECT Master.*
FROM main_iteminstance Master
INNER JOIN main_iteminstance Child
ON Child.master_id = 33568 AND ((Master.id = Child.id) OR (Master.tv_series_id = Child.id))

答案 2 :(得分:0)

您将使用相关的子查询,如下所示:

select * 
from main_iteminstance as m
where exists (
    select *
    from main_iteminstance as s
    where (m.id = s.id or m.id = s.tv_series_id)
    and s.master_id=33568)

此查询与您提供的查询相比如何执行取决于很多事情,但它更易于维护和清晰,因为所有内容都在一个地方指定。