开发者

MySQL Limiting a query to one consistent value

My current query returns a table like:

+------------+
value1 | ....
value1 | ....
value2 | ....
value3 | ....
+------------+

I want:

+------------+
value1 | ....
value1 | ....
+------------+

I want to only receive all rows with the first value. Normally I would do a WHERE clause if I knew that value, and I cannot use a LIMIT because e开发者_Python百科ach value has a different number of rows.

Right now My query looks like:

SELECT u.*, n.something, w.* 
  FROM ... AS u, ... AS n, ... AS w 
 WHERE u.id = n.id 
   AND w.val = n.val 
   AND u.desc LIKE '%GET REQUEST VARIABLE%'

This works great, except I get way too many rows and using PHP to do this ruins code portability and is superfluous.


Not sure but I think you might be able to get it with this:

SELECT u.*, n.something, w.*
FROM ... AS u
JOIN ... AS n ON u.id = n.id
JOIN ... AS w ON w.val = n.val
JOIN (
  SELECT col
  FROM ... AS u2
  WHERE u2.desc LIKE ?
  LIMIT 1
) AS u2 ON u2.col = u.col

where the ... in the inner SELECT is the same table aliased to u before.

EDIT: One more thing: I assumed col is different for different desc values; if not, you would have to repeat the WHERE in the outer SELECT as well.

(If you're not familiar with prepared statements, ? is where your '%...%' would go... and don't forget to escape it against Bobby Tables; if you are, of course, the library will do it for you :) )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜