[英]add WHERE condition to a 3 table LEFT JOIN query…?
I'm working my way through the php world but still finding my feet. 我正在努力通过php世界,但仍能找到自己的脚。 I've written a query that works nicely for collecting what i need from mysql, but I just cannot get it to work with a WHERE
condition. 我编写了一个查询,该查询很好地用于从mysql收集我需要的东西,但是我无法使其在WHERE
条件下工作。 Any help would be much appreciated! 任何帮助将非常感激!
Here's my working query without the WHERE
condition: 这是我没有WHERE
条件的工作查询:
SELECT foo.*, users.name, SUM(bar.amt) Total FROM foo
LEFT JOIN bar ON foo.id = bar.foo_id
LEFT JOIN users ON foo.foo_owner_id = users.id
LIMIT 16 GROUP BY foo.id"
And here's what I think should work to add the WHERE
condition but doesn't work... 这是我认为应该添加WHERE
条件但不起作用的内容...
SELECT foo.*, users.name, SUM(bar.amt) Total FROM foo
WHERE foo.category = $var LEFT JOIN bar ON foo.id = bar.foo_id
LEFT JOIN users ON foo.foo_owner_id = users.id LIMIT 16 GROUP BY foo.id"
Any and all suggestions are welcome, thanks!! 任何和所有建议都欢迎,谢谢!
非常简单:所有WHERE
条件都应放在所有JOIN
之后。
You need to put the WHERE
clause after all the joined tables. 您需要将WHERE
子句放在所有联接的表之后。 Hence 于是
SELECT foo.*, users.name, SUM(bar.amt) Total
FROM foo
LEFT JOIN bar ON foo.id = bar.foo_id
LEFT JOIN users ON foo.foo_owner_id = users.id
WHERE foo.category = $var
GROUP BY foo.id
LIMIT 16;
You probably also want the LIMIT
clause to be last. 您可能还希望LIMIT
子句位于最后。
use 采用
SELECT
foo.*,
users.name,
SUM(bar.amt) Total
FROM foo
LEFT JOIN bar ON foo.id = bar.foo_id
LEFT JOIN users ON foo.foo_owner_id = users.id
WHERE foo.category = $var
GROUP BY foo.id
LIMIT 16
when you are using left or right join then always use where clause after joins. 当您使用左连接或右连接时,请在连接后始终使用where子句。
SELECT foo.*, users.name, SUM(bar.amt) Total
FROM foo
LEFT JOIN bar ON foo.id = bar.foo_id
LEFT JOIN users ON foo.foo_owner_id = users.id
WHERE foo.category = $var
GROUP BY foo.id
LIMIT 16;
even if u want order by id etc use it before LIMIT 即使您想按ID等进行订购,也要在LIMIT之前使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.