2017-02-04 55 views
0

当语句结尾处的WHERE子句未包括时,子查询限制结果完美。我知道子查询LIMIT首先发生,然后在该结果集上触发WHERE子句,并且这是对子查询的限制/限制。子查询LIMIT在执行子查询之外的WHERE时导致问题

我需要的是比我更有经验的人帮助兄弟用LIMIT检索记录,并且能够通过WHERE子句限制结果集。让我知道这是不是很好解释。

我也搜遍了互联网寻找答案几个小时,没有运气。你的时间值得赞赏。

编辑:添加上SQLfiddle原油例如:http://sqlfiddle.com/#!9/2de563/4

SELECT * 
    FROM (SELECT * FROM parent_products LIMIT 10) pp 
    INNER JOIN products_variants pv ON pv.parent_id=pp.parent_id 
    INNER JOIN products p ON p.id=pv.product_id 
    INNER JOIN product_types pt ON pt.product_type_id=p.product_type 
    LEFT JOIN team_list t ON pp.team_id=t.team_id 
    LEFT JOIN photos ph ON ph.product_id=p.id 
    LEFT JOIN product_attributes pa ON pa.product_id=pv.product_id 
    LEFT JOIN attributes a ON a.id=pa.attribute_id 
    LEFT JOIN product_attribute_options po ON po.product_attribute_option_id=a.parent_id 
    WHERE t.team_id=100 AND p.active='y'; 

解释选择: enter image description here

+0

如果可能分享您的样本数据的脚本,将很容易调试查询 –

+0

@ChintanUdeshi我希望我可以...这是一个工作数据库......再加上数据结构是顶起来的。基本上这是与父母/子女的1-n关系。我需要限制父母,但不包括孩子数量的限制(上面的查询)。但是一旦添加WHERE子句,由于LIMIT选择前10个结果并针对这10个结果运行WHERE,因此结果为空。因此没有结果。希望这个解释能帮助更多。 – Binary101010

+0

yes从(SELECT * FROM parent_products LIMIT 10)中选择的前10个结果在相应产品中没有Active ='y',因此当您应用条件时没有数据到达 –

回答

0
Below query will give you the expected output 

SELECT * FROM (SELECT users.id,users.name FROM users 
LEFT JOIN map ON users.id=map.user_id 
LEFT JOIN locations ON locations.location_id=map.location_id 
INNER JOIN type ON locations.type=type.id 
WHERE type.id=1 limit 3) users 
LEFT JOIN map ON users.id=map.user_id 
LEFT JOIN locations ON locations.location_id=map.location_id 
INNER JOIN type ON locations.type=type.id 
where type.id=1; 
+0

没有ORDER BY的限制是相当无意义的 – Strawberry

+0

输出需要前3个用户无论如何 –

+0

这选择3行。但不一定是前3行 – Strawberry