有没有办法按计算值过滤而不将其包装在另一个选择中?

时间:2013-05-30 11:59:32

标签: mysql

假设我有一个像

这样的简单查询
SELECT ID, Name, SUM(qty * price) as Value
FROM Docs 
WHERE Name like '%something%' OR Value like '%something%'
GROUP BY ID, Name

表格Docs记录了每个产品的库存记录:

ID: the id of the document through which the product was released from the inventory (for example an invoice or a delivery note)  
Name: the name of the document  
qty: the number of units that were released  
price: the unit price of the product in said inventory  

(实际表格比这复杂得多,但为了清晰起见,我简化了很多)

正如您所看到的,我发布的查询是全面搜索。我想列出所有文档的ID,名称和总值,其名称或值类似于某些用户输入。但是我实际上无法在WHERE子句中使用Value列。

我可以将它包装在另一个select * FROM ()中并对其进行搜索。但是我必须处理的查询要复杂得多,以这种方式改变它会带来很多麻烦。

如果我想进行这种搜索,有没有办法避免包装整个查询?

4 个答案:

答案 0 :(得分:1)

HAVING会做同样的事情吗?

SELECT ID, Name, SUM(qty * price) as Value
FROM Docs
HAVING Value like '%something%' OR Name like '%something%'

答案 1 :(得分:1)

我们试试

SELECT ID, Name, SUM(qty * price) as Value
FROM Docs 
having Value like '%something%' or Name like '%something%' 

答案 2 :(得分:1)

如果你不想让“从选择中选择”UNION可以帮到你:

(SELECT ID, Name, SUM(qty * price) as Value
FROM Docs 
WHERE Name like '%something%')
UNION
(SELECT ID, Name, SUM(qty * price) as Value
FROM Docs 
HAVING SUM(qty * price) like '%something%')

答案 3 :(得分:0)

SELECT ID, Name, SUM(qty * price) as Value
FROM Docs 
WHERE Name like '%something%' OR Value like '%something%'
GROUP BY ID, Name

此查询唯一的问题是MySQL不允许在WHERE子句中使用别名。

所以你可以简单地在WHERE子句中重复计算,它应该可以工作:

WHERE Name like '%something%' OR SUM(qty * price) like '%something%'

不要担心在查询中进行两次相同的计算 - 查询优化器应该识别它并且仍然只计算一次值。

(顺便说一句,在数值上使用LIKE似乎有点奇怪 - 其他比较运算符,例如=<>可能更合适。)