Sunday, June 24, 2012

MySQL Joins (Left join, right join, inner join, straight_join, natural_join)

Today we are going to discuss MySQL Joins (Left Join, Right Join, Inner Join, Self Join and Natural Join) in additional to these, we will touch the Straight Join (STRAIGHT_JOIN)

Let's we begin from joins syntax. The syntax is as follows:
SELECT 
   t1.col1, 
   t2.col2
FROM
   table1 AS t1
   JOIN 
      table2 AS t2
         ON (t1.col1 = t2.col2)
WHERE t1.col1=t2.col2
SELECT as usual, then going FROM table JOIN, join another table to the first table and then ON. join ON (condition) after maybe used WHERE clause, but not necessary.
In total ON is equal to WHERE and is not limited to one condition, then you can append GROUP, HAVING, LIMIT, etc.

Now let's discuss the joins type, they are few and we will talk about each of them.
MySQL's INNER JOIN / JOIN
INNER JOIN is equal to JOIN. next 2 statements are equal by their meaning:
SELECT 
   t1.col1, t1.col2
FROM
   table1
   INNER JOIN table2
   ON (t1.col1 = t2.col2)

# previous query is equal to next
SELECT 
   t1.col1, t1.col2
FROM
   table1
   JOIN table2
   ON (t1.col1 = t2.col2)

INNER JOIN return rows when there is at least one match in both tables, otherwise the query wouldn't return results.

MySQL's LEFT JOIN
LEFT JOIN return ALL rows from the left table even if no match found on the right table. example:
SELECT 
   t1.col1, t1.col2
FROM
   table1 # returns all rows from table 1
   LEFT JOIN table2 # even f no match in table 2
   ON (t1.col1 = t2.col2)


MySQL's RIGHT JOIN
RIGHT JOIN is a reversed join of left, returns all rows from right table even if no match found in left. refer to previous example of left join.

NATURAL JOIN
NATURAL JOIN acts as INNER JOIN, the difference is that INNER JOIN may return any of the columns while NATURAL JOIN will return only these with same name in both tables.
NATURAL JOIN also doesn't apply ON clause.

SELF JOIN
SELF JOIN is a kind of JOIN, SELF JOIN can be any of these, INNER, LEFT or RIGHT.
SELF JOIN joins same table how many times you required. example:
SELECT
   *
FROM
   table1 AS t1
   JOIN table1 AS t2
      ON (t1.col1<>t2.col1)

In this example we joined same table, this is kind of implementation of SELF JOIN.

STAIGHT_JOIN
STRAIGHT_JOIN is a keyword that tells (forces) MySQL's Optimizer to join tables in order they are type in the query, this have it's benefits and disadvantages.
This kind of join may be seen very useful however no one will advice to use them always.
Use EXPLAIN/EXPLAIN EXTENDED to understand whether to use it or not.
SELECT
   *
FROM
   table1 AS t1
   STRAIGHT_JOIN table1 AS t2
      ON (t1.col1<>t2.col1)

In this example, no matter what will happen, optimizer will read t1 and then will read table2 in an inner loop.


Have fun playing these things ;-)
Sincerely,
VR.

Friday, June 22, 2012

Tablesorter Installation Detailed HOW TO

Hi, Dear Readers.
Today I will explain HOW TO INSTALL TABLESORTER Plugin.
For real, the basic is very easy to install.
In case You need to install also pager, make sure you read also next article: TableSorter Pager plugin tutorial and settings also written by me.

Let's We begin
As usual we will start with data gathering and proceed.

Data Gathering Download the Tablesorter plugin from here: Tablesorter

Download Tablesorter's Default CSS from here: Tablesorter's CSS, later on you can change the look&feel as you wish

And the images used for styling: Here
And here -> ASC Image
And here -> DESC Image


Well, At this point we got all information that we need for beginning with tablesorter plugin. As i told it is very easy and very extendable.


Prepare Data
Place your fresh downloaded images into the images directory and adjust the CSS to point to images and read them.
Place your tablesorter.js into the directory you keep javascript files in (assume js)
Place your css file into css folder (we assume css)


Tablesorter Installation
We assume that we want to setup tablesorter plugin at index.html
We also assume that you have jQuery previously installed on this page.
Place your tablesorter.js into page, we prefer before (body end)
Place your CSS file in the head of the page (between and tags)
My file currently looks like that:



   
   


   
Name
Student01
Student01
Name
This example shows how to instantiate a basic instance of tablesorter, the reason to use only 2 values is to test it quick if it works with string values and sorts as expected. after such quick "DRY" Run, you can begin adding/generating data into table.
But do it ONLY AFTER You ensure that this works with basic example.


Tablesorter Options/Settings
Here i take the clear descriptions from tablesorter, but these that may be hard for you to undesrtand - i will explain deeply.
/**
 * cssHeader -> optional parameter. You can support here class name that will 
 * be applied to  tag inside header (inside ).
 * Description taken from Tablesorter
 **/
cssHeader: "header",

/**
 * cssAsc -> optional parameter, You can support class name to be applied to a
 * heading  element when sorting ASC mode.
 */
cssAsc: "headerSortUp",

/**
 * cssDesc -> optional parameter, You can support class name to be applied to a
 * heading  element when sorting DESC mode.
 */
cssDesc: "headerSortDown",

/**
 * cssChildRow -> unknown parameter for me, never used =) Touches some of the css
 * That long i worked with tablesorter, never used it - I believe you won't use it
 * too, at least at this time. :)
 */
cssChildRow: "expand-child",

/**
 * sortInitialOrder -> optional parameter saying order type in time of instantiation 
 * ascending/descending, possible values is "asc" or "desc", by default "asc".
 */
sortInitialOrder: "asc",

/**
 * sortMultiSortKey -> optional parameter to redefine the key to hold to select
 * multiple fields for sorting. default "shiftKey"
 * this one is a bit problematic ;)
 */
sortMultiSortKey: "shiftKey",

/**
 * sortForce -> optional parameter -> array containing forced sorting rules.
 */
sortForce: null,

/**
 * sortAppend -> optional, This option let's you specify a default sorting rule,
 * which is appended to user-selected rules (sortForce)
 */
sortAppend: null,

/**
 * String textExtraction (optional) A string of the text-extraction
 * method to use. For complex html structures inside td cell set this
 * option to "complex", on large tables the complex option can be slow.
 * Default value: "simple"
 */
textExtraction: "simple",

/**
 * Widgets -> optional parameter, allows you to specify widgets to be applied to
 * current tablesorter instance
 */
widgets: [],

/**
 * widgetZebra -> optional these params is a CSS classes for odd and even for 
 * applied widget "zebra"
 */
widgetZebra: {css: ["even", "odd"]}, 

/**
 * headers -> optional allows you to tell the sorter whether to sort specified field
 * or not, if yes which sorter to apply to it, sort order, etc. very useful param
 * example: $('#domelement').tablesorter({headers: { 
 *                   0: { sorter: false}, 
 *                   1: {sorter: false} 
 *                   }
 *          });
 */
headers: {}, 

/**
 * widthFixed -> optional, boolean flag whether table is at fixed width or resizable
 */
widthFixed: false,

/**
 * cancelSelection -> optional, boolean, defines whether tablesort should cancel
 * heading selecting or not.
 */
cancelSelection: true,

/**
 * sortList -> optional, array, This option let's you specify a default sorting rule.
 * default value is null
 */
sortList: [],

/**
 * headerList -> optional, array, List of Header? ) IDK what is that param.
 */
headerList: [],

/**
 * dateFormat -> optional, string, sets default format for dates found in your table
 * allows you to redefine the date format to use in sorting.
 */
dateFormat: "us",

/**
 * decimal -> optional, string, part of regex which characters are in decimal number
 */
decimal: '/\.|\,/g',

/**
 * selectorHeaders -> optional, string, holds a selector of heading th
 */
selectorHeaders: 'thead th',

/**
 * debug, optional, boolean, var name says by itself ;)
 */
debug: false

Now that you are ready to go with tablesorter, i can tell few more words about it
Not every field may be sorted, even if it looks like decimal or as date, in case you need to write custom parser, you are invited to read next article TableSorter Month/Year sorter (Custom Sorting), this one can be a good example of custom sorter coding.
Also Tablesorter allows to get extended with pagination plugin called Tablesorter Pager, The tutorial on Pager & options/settings is here: TableSorter Pager plugin tutorial and settings

Have fun playing with tablesorters settings.

Sincerely, Ruskevych Valentin

TableSorter Pager plugin installation and settings

Hi, My Dear Public. Today I want to talk how to work with Pager plugin for TableSorter. Tablesorter is very famous jQuery based plugin for sorting tabular data and is extendable a lot and We will explain HOW TO apply one of the standard tablesorter's plugins - Pager

In this tutorial we assume that you already have installed TableSorter on your page and is working otherwise you can read detailed tutorial on Tablesorter installation tutorial.

Data Gathering
First we will need to download the pager plugin located at Tablesorter Pager Plugin

Tablesorter's pager doesn't require any default css, but you can create one for you and work with, for example if you wish to use images (next,prev,first,last) as one sprite, you are free add your own css to current classes.

Now you need to get Tablesorter Pager's HTML. This is current HTML and as far as i remember never changed:)


Now we will need these 4 Images user in Tablesorter Pager
Download them here:
http://tablesorter.com/addons/pager/icons/first.png
http://tablesorter.com/addons/pager/icons/prev.png
http://tablesorter.com/addons/pager/icons/next.png
http://tablesorter.com/addons/pager/icons/last.png


Ok, At this point we got all we need to proceed to Tablesorter's Pager Installation Tutorial itself.

Now we should adjust and set up Tablesorter Pager's HTML: adjust
and like that with each image in HTML we just got. /path/to_your/images/first.png -> assume you stored images in images/pager, so the path to first.png will look like


NOTE: Don't change the class names (!), it is very important. At this step copy your tablesorter pager's HTML and past it at the place you want it to be around your data table, for example at the bottom. right or left or top left, etc. As you wish it looks better in your design of the page.

Ok, We got installed HTML, now we need to set JS and Instantiate the Pager. You can install the pager directly such as
Don't forget to replace the path to your tablesorter.pager.js
I can suggest for FrontEnd optimization purposes to append tablesorter.pager.js contents to tablesorter's code at the end.
Open tablesorter.pager.js copy it's content, go to tablesorter.js -> at the end of file past the pager's content, so you will economy one browser's request.

Instantiate:
You can instantiate them separately, but i prefer to chain, to not cause the mess in code.Chain will allow you to always find when it's being instantiated, especial in cases when you need few tablesorters with pager
We assume you have instatiated the table sorter on #table (id="table")
/**
 * in your (function(){ instance code });
 * or in your $(document).ready(function(){ instantiate code });
 * add the following code
 * pager's HTML wrapper should have id="pager" to work, later on we 
 * will explain how to change this behavior.
 **/
$('#table').tablesorter().tablesorterPager({container: $("#pager")});


Options/Settings:
To tell you the truth i didn't experiment with few of these options, but i will explain these i did.
/**
 * Starting page size (10 results now), you make it 20 results while starting pager
 * $('#table').tablesorter().tablesorterPager({container: $("#pager"),size:20});
 * and set first size in HTML to be 20 and the rest
 **/
size: 10, 

offset: 0, // int offset Used for fixing position in PX, but w/o word px. 

/**
 * Page parameter, used to set pager's current page. You can use it while starting
 * pager, to set for example to page 3 so u need to set 2
 * $('#table').tablesorter().tablesorterPager({container: $("#pager"),page:2});
 */
page: 0,

/**
 * Container parameter used to indicate the container of pager. Always use it.:)
 * $('#table').tablesorter().tablesorterPager({container: $("#pager")});
 */
container: null,

/**
 * Next 4 properties is styling, you can use them to change class names of buttons
 * You can also override them to IDs if you have collision when running few pagers.
 * $('#table').tablesorter().tablesorterPager({container: $("#pager"),cssNext:'#p1next'});
 * etc...
 */
cssNext: '.next',
cssPrev: '.prev',
cssFirst: '.first',
cssLast: '.last',

/**
 * Separrator between pager, eg. 1/7 indicates 1 of 7 pages, you can set it to " of "
 * so your pager will display 1 of 7. :)
 * $('#table').tablesorter().tablesorterPager({container: $("#pager"),seperator:" of "});
seperator: "/",

positionFixed: true, // This param also used for fixing position 



Tablesorter & Pager Troubleshooting:
If you meet any problem with tablesorter and/or pager that are not working.

First check if the ID's on instance meet the IDs on DOM Elements (eg. pager's div, table)
Remove options one by one, so you may detect exact option caused to bug.
If this didn't help, don't instantiate pager, maybe your browser can't find pager's script.
Try removing all the data from table, leave just one result and make sure there's not special charaters that may cause to something work wrong.



Have fun playing these setting. Sincerely, VR