WHERE子句中嵌套SQL语句的结果

时间:2014-06-27 22:07:15

标签: mysql sql

我有一张beats表格,每个节拍中有多行包含pricing表格中的不同价格。

SELECT b.id, b.name,
(SELECT p.price FROM pricing as p WHERE p.license = 1 AND p.beat_id = b.id) as price_1,
(SELECT p.price FROM pricing as p WHERE p.license = 2 AND p.beat_id = b.id) as price_2
FROM beats as b 
WHERE b.added > 0 
AND b.active = 1 
AND b.deleted = 0 
AND price_1 > 0
ORDER BY b.id DESC 
LIMIT 50

我正在尝试确保仅在beat大于0时检索price_1

这不起作用,因为您不能在WHERE子句中使用嵌套SQL语句的结果,但我已尝试HAVING price_1 > 0,但这也不起作用。

如何测试price_1price_2

3 个答案:

答案 0 :(得分:1)

您可以将该条件移至having子句。这是MySQL的一项功能,不受其他数据库的支持:

SELECT b.id, b.name,
       (SELECT p.price FROM pricing as p WHERE p.license = 1 AND p.beat_id = b.id) as price_1,
       (SELECT p.price FROM pricing as p WHERE p.license = 2 AND p.beat_id = b.id) as price_2
FROM beats as b 
WHERE b.added > 0 AND b.active = 1 AND b.deleted = 0 
GROUP BY b.producer 
HAVING price_1 > 0
ORDER BY b.id DESC 
LIMIT 50;

答案 1 :(得分:1)

您可以使用JOIN:

SELECT b.id, b.name, p1.price AS price_1, p2.price AS price_2
FROM beats AS b
JOIN pricing AS p1 ON p1.beat_id = b.id
JOIN pricing AS p2 ON p2.beat_id = b.id
WHERE b.added > 0 AND b.active = 1 AND b.deleted = 0
  AND p1.license = 1 AND p1.price > 0
  AND p2.licence = 2
GROUP BY b.producer
ORDER BY b.id DESC
LIMIT 50

答案 2 :(得分:0)

在没有表的DML的情况下(例如,如果group by b.producer看起来像主键,则需要b.id不清楚为什么需要SELECT b.id, b.name, p1.price as price_1, (SELECT p.price FROM pricing as p WHERE p.license = 2 AND p.beat_id = b.id) as price_2 FROM beats as b JOIN pricing p1 ON (p1.license = 1 AND p1.beat_id = b.id AND p1.price > 0) WHERE b.added > 0 AND b.active = 1 AND b.deleted = 0 GROUP BY b.producer ORDER BY b.id DESC LIMIT 50 ),最小的改变是拉出嵌套查询进入子查询并在其上进行内连接

b.id

假设group by b.producer是主键,我也会放弃{{1}},将price_2查询拉入连接可能是明智的(尽管再次不了解您的数据和DML我不能如果它应该是内部或左外部连接,则说明确定。)