Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

php - LIMIT results in MySQL?

ok; this has been frying my brain for hours. I think I might need a sub query, but I'm not that advanced at this kind of thing so any help or pointers in the right direction would be greatly appreciated.

Here's the Query I have....

$query = "SELECT * FROM events WHERE event_type = 'Christmas Listings' AND event_active='Yes' ORDER BY event_date ASC LIMIT 5";
$result= mysql_query($query); 

OK... now for the plain english bit on what I want to achieve (to understand what I'm trying to achieve):

  1. I want to check the event type ('event_type') is what I'm getting (ie. Christmas Listings) as there are multiple types in this column.

  2. I want to check the event is active ('event_active') is Yes(the data in this field is Yes/No).

  3. I want to order them by the ('event_date') ASC (the data in this field is yyyy-mm-dd) so they show the latest entry by its date from the DB.

  4. I want to LIMIT (or in some way control the output) the results to only have 5 results displayed when running this kind of query through a WHILE statement.

OK, this all works BUT; when I get to the actual output display, i'm having a shaky output in how many results are actually display... What happens is if I have multiple events which are switched off, as in event_active is 'Off' then its almost like the argument is counting from the all the results that are (including event_active='Off') and consequently not showing how I expect them to display?

Hope this makes sense.... Any help would be gratefully received.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
SELECT * 
FROM events 
WHERE event_type = 'Christmas Listings' AND event_active='Yes' 
ORDER BY event_date 
LIMIT 0, 5

so your statement is easyer to read..

  1. You shoul use 1 / 0 instead of Yes / no
  2. The Limit does not count all lines! First step - doing the query including WHERE Second step - ORDER BY Third step - LIMIT If you have set an index on the colum you sort. The sort will stop after 5 lines, also means - it get faster
  3. The ASC in the ORDER BY command is not necessary, because ASC is default

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...