[英]Find records where field is greater than all values in a set in MySQL
I have a table T1
with columns C1, C2, C3, C4
and T2
with columns C1
and D1
. 我有一个具有列
C1, C2, C3, C4
和T2
的表T1
,具有列C1
和D1
。 I'd like to select all rows in T1
where appropriate row in T2
has D1
greater than C2
, C3
and C4
. 我想选择
T1
中的所有行,其中T2
中的适当行的D1
大于C2
, C3
和C4
。
I tried something like this 我尝试过这样的事情
SELECT C1,C2,C3,C4 FROM T1
WHERE (SELECT D1 FROM T2 WHERE C1=T1.C1)>(C2,C3,C4)
and this 和这个
SELECT C1,C2,C3,C4 FROM T1
WHERE (SELECT D1 FROM T2 WHERE C1=T1.C1)>MAX(C2,C3,C4)
but what I get is an error in syntax. 但是我得到的是语法错误。 I could write WHERE clause like this:
我可以这样写WHERE子句:
WHERE (SELECT D1 FROM T2 WHERE C1=T1.C1)> C2
AND (SELECT D1 FROM T2 WHERE C1=T1.C1)> C3
AND (SELECT D1 FROM T2 WHERE C1=T1.C1)> C4
However, running the same subquery 3 times is unnecessary for it always returns the same result. 但是,不必运行3次相同的子查询,因为它总是返回相同的结果。
Could anyone help? 有人可以帮忙吗? :)
:)
You want the GREATEST()
function, which allows multiple arguments. 您需要
GREATEST()
函数,该函数允许多个参数。 MAX() accepts only a single argument, and is intended for aggregate operations MAX()仅接受单个参数,并用于聚合操作
SELECT *
FROM T1
...
WHERE T2.D1 > GREATEST(C1,C2,C3,C4)
If it helps, MAX() works "vertically", on a single field in a result set. 如果有帮助,MAX()在结果集中的单个字段上“垂直”运行。 GREATEST() works "horizontally", and operates within a single record.
GREATEST()是“水平”运行的,并且在单个记录中运行。
Also if I understand correctly, your key is C1... you need to join your tables properly.. 同样,如果我理解正确,那么您的密钥是C1...。您需要正确连接表。
SELECT T1.*
FROM T1
LEFT JOIN T2 USING (C1)
WHERE D1 > GREATEST(C2,C3,C4)
I put together a little SQL Fiddle for you here and tried to replicate my understanding of what you are asking. 我在这里为您整理了一些SQL Fiddle,并尝试复制我对您所要问的理解。
Here is the query I used: 这是我使用的查询:
SELECT one.* FROM one, two
WHERE (two.frags > one.size)
AND (two.frags > one.weight)
AND (two.frags > one.height)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.