MySQL - 我的JOIN查询中的WHERE子句有什么问题?

时间:2012-12-01 09:00:38

标签: mysql date where

我设法拼凑了一个连接语句,给我一个显示整个数据库的表。现在我需要将结果缩小到最近30天,但我不能为我的生活找出如何将此限制用于查询。

现在我有:

select customers.name, customers.email, orderinfo.orderno, orderinfo.orderdate, status.state, orderinfo.lastupdate 
from customers 
where orderinfo.orderdate = curdate() 
inner join orderinfo on customers.id=orderinfo.fk_id 
inner join status on orderinfo.fk_code=status.code 
order by customers.name;

...试图将其缩小到向我显示今天的所有记录,但即使这样也行不通。我看到有很多方法可以完成30天的工作,但是我遇到的最麻烦的部分就是让WHERE子句在这个查询中完全可用。

感谢您的任何建议!

4 个答案:

答案 0 :(得分:1)

WHERE子句需要在ORDER BY之前和所有连接之后。

select customers.name, customers.email, orderinfo.orderno, orderinfo.orderdate, status.state, orderinfo.lastupdate 
from customers 
inner join orderinfo on customers.id=orderinfo.fk_id 
inner join status on orderinfo.fk_code=status.code 
where orderinfo.orderdate = curdate() 
order by customers.name;

答案 1 :(得分:0)

您未在orderinfo部分中指定FROM

select customers.name, customers.email, orderinfo.orderno, orderinfo.orderdate, status.state, orderinfo.lastupdate 
from customers 
inner join orderinfo on customers.id=orderinfo.fk_id 
inner join status on orderinfo.fk_code=status.code 
where orderinfo.orderdate = curdate() 
order by customers.name;

答案 2 :(得分:0)

SELECT customers.name, customers.email, orderinfo.orderno, orderinfo.orderdate, status.state, orderinfo.lastupdate 
FROM customers 
INNER JOIN orderinfo ON customers.id=orderinfo.fk_id 
INNER JOIN status ON orderinfo.fk_code=status.code 
WHERE orderinfo.orderdate = curdate() 
ORDER BY customers.name;

WHERE需要在JOINS之前和ORDER BY之前

答案 3 :(得分:0)

你的内部联接应该在你的where子句

之前
select customers.name, customers.email, orderinfo.orderno, orderinfo.orderdate, status.state, orderinfo.lastupdate 
from customers 
inner join orderinfo on customers.id=orderinfo.fk_id 
inner join status on orderinfo.fk_code=status.code 
where orderinfo.orderdate = curdate() 
order by customers.name;

如果您需要先使用条件进行查询,则需要子查询

Select * From
(
   select customers.name, customers.email, orderinfo.orderno, orderinfo.orderdate, status.state, orderinfo.lastupdate 
   from customers
   where orderinfo.orderdate = curdate()  
) customers
inner join orderinfo on customers.id=orderinfo.fk_id 
inner join status on orderinfo.fk_code=status.code 
order by customers.name;