Tuesday, July 26, 2011

Advanced MySQL Queries

             I will use some examples to show how the stuff is going to work. You just replace your table names and field names.

Using SELECT
 
SELECT * FROM pets WHERE name LIKE '%T%' AND gender LIKE 'Female';

SELECT * FROM pets WHERE (breed LIKE 'cat' AND gender LIKE 'male') OR (breed LIKE 'dog' AND gender LIKE 'male');


Order By


SELECT * FROM pets ORDER BY dateofbirth;
SELECT * FROM pets ORDER BY gender DESC;


Limit

SELECT * FROM pets LIMIT 3;
SELECT * FROM pets LIMIT 2, 5;

      The first example will return the first 3 rows from the pets table. The second example will return 4 rows (rows 3-6, which are the 2nd, 3rd, 4th and 5th rows since the offset is 0).

Distinct

 SELECT DISTINCT name FROM pets ORDER BY name;

      Used to avoid displaying pets with same name.

Count

 SELECT COUNT(*) FROM pets;

 SELECT COUNT(*) FROM pets WHERE name LIKE 'Sylvester'; 

 SELECT gender, COUNT(*) FROM pets GROUP BY gender; 

No comments:

Post a Comment