<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mukesh Chapagain&#039;s Blog &#187; SQL</title>
	<atom:link href="http://blog.chapagain.com.np/tag/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.chapagain.com.np</link>
	<description>PHP Magento jQuery SQL Wordpress Joomla Programming &#38; Tutorial</description>
	<lastBuildDate>Tue, 07 Feb 2012 00:54:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>MySQL Database: Foreign Key Understanding and Implementation</title>
		<link>http://blog.chapagain.com.np/mysql-database-foreign-key-understanding-and-implementation/</link>
		<comments>http://blog.chapagain.com.np/mysql-database-foreign-key-understanding-and-implementation/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 02:22:52 +0000</pubDate>
		<dc:creator>Mukesh</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[cascade]]></category>
		<category><![CDATA[foreign key]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://blog.chapagain.com.np/?p=1262</guid>
		<description><![CDATA[Some definitions of foreign key:- A FOREIGN KEY in one table points to a PRIMARY KEY in another table. A foreign key is a field in a relational table that matches the primary key of another table. The foreign key can be used to cross-reference tables. A table may have multiple foreign keys, and each [...]


<strong>Related posts:</strong><ol><li><a href='http://blog.chapagain.com.np/alter-mysql-table-to-add-drop-column-add-foreign-key/' rel='bookmark' title='Permanent Link: Alter MySQL table to add &#038; drop column &#038; add Foreign Key'>Alter MySQL table to add &#038; drop column &#038; add Foreign Key</a></li>
<li><a href='http://blog.chapagain.com.np/very-useful-sql-queries-with-joins/' rel='bookmark' title='Permanent Link: 10 Very Useful SQL Queries with JOINS'>10 Very Useful SQL Queries with JOINS</a></li>
<li><a href='http://blog.chapagain.com.np/backup-and-recovery-of-mysql-database/' rel='bookmark' title='Permanent Link: Backup and Recovery of MySQL database'>Backup and Recovery of MySQL database</a></li>
<li><a href='http://blog.chapagain.com.np/sql-error-cannot-insert-the-value-null-into-column-column-does-not-allow-nulls-insert-fails/' rel='bookmark' title='Permanent Link: SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.'>SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.</a></li>
<li><a href='http://blog.chapagain.com.np/magento-how-to-delete-system-attribute/' rel='bookmark' title='Permanent Link: Magento: How to delete System Attribute?'>Magento: How to delete System Attribute?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Some definitions of foreign key:-</p>
<blockquote><p>A FOREIGN KEY in one table points to a PRIMARY KEY in another table.</p>
<p>A foreign key is a field in a relational table that matches the primary key of another table. The foreign key can be used to cross-reference tables. A table may have multiple foreign keys, and each foreign key can have a different referenced table.</p>
<p><span id="more-1262"></span></p>
<p>A Foreign Key is a Referential Constraint between two tables. A Referential Constraint or Referential Integrity is a property of data which, when satisfied, requires every value of one attribute (column) of a relation (table) to exist as a value of another attribute in a different (or the same) relation (table).
</p></blockquote>
<p>For MySQL, to support foreign key, the table type should be &#8216;<strong>InnoDB</strong>&#8216;. Therefore, when we are cross-referencing two tables through foreign key, both the tables must be InnoDB tables and they must not be Temporary tables.</p>
<p><strong>InnoDB </strong> also supports foreign key references within a table. The referencing and referenced table may be the same table, i.e. the foreign key refers back to the same table. Such a foreign key is known as a self-referencing or recursive foreign key.</p>
<p>When the user attempts to delete or update a row from a parent table, and there are one or more matching rows in the child table, InnoDB handles this through &#8220;<strong>Referential Action</strong>&#8220;. There are five options regarding the action to be taken. If <strong>ON DELETE</strong> or <strong>ON UPDATE</strong> are not specified, the default action is <strong>RESTRICT</strong>.</p>
<blockquote><p>
<strong>CASCADE</strong>: Delete or update the row from the parent table and automatically delete or update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported. </p>
<p><strong>SET NULL</strong>: Delete or update the row from the parent table and set the foreign key column or columns in the child table to NULL. This is valid only if the foreign key columns do not have the NOT NULL qualifier specified. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.</p>
<p><strong>NO ACTION</strong>: In standard SQL, NO ACTION means no action in the sense that an attempt to delete or update a primary key value is not permitted to proceed if there is a related foreign key value in the referenced table. InnoDB rejects the delete or update operation for the parent table.</p>
<p><strong>RESTRICT</strong>: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause. The main difference between NO ACTION and RESTRICT is that with NO ACTION the referential integrity check is done after trying to alter the table. RESTRICT does the check before trying to execute the UPDATE or DELETE statement. However, in MySQL, foreign key constraints are checked immediately, so NO ACTION is the same as RESTRICT.</p>
<p><strong>SET DEFAULT</strong>: Similar to SET NULL, the foreign key values in the referencing row are set to the column default when the referenced row is updated or deleted. This action is recognized by the parser, but InnoDB rejects table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.
</p></blockquote>
<p>Here, I will be implementing the foreign key <strong>CASCADE </strong>update and delete.</p>
<p><strong>CASCADE</strong>:-</p>
<p>Whenever rows in the master (referenced) table are deleted, the respective rows of the child (referencing) table with a matching foreign key column will get deleted as well. This is called a cascade delete.</p>
<p>Example Tables: test_customer(customer_id, name, address) and test_order(order_id, customer_id, status)</p>
<p>test_customer is the master table and test_order is the child table, where &#8216;customer_id&#8217; is the foreign key in test_order and represents the customer who placed the order. When a row of test_customer is deleted, any test_order row matching the deleted test_customer&#8217;s customer_id will also be deleted.</p>
<p><strong>Create Tables</strong></p>
<p><code>CREATE TABLE test_customer (<br />
    customer_id int(10) unsigned NOT NULL auto_increment,<br />
    name varchar(100),<br />
    address varchar(100),<br />
    PRIMARY KEY (customer_id)<br />
) ENGINE=InnoDB;</p>
<p>CREATE TABLE test_order (<br />
    order_id int(10) unsigned NOT NULL auto_increment,<br />
    customer_id int(10) unsigned NOT NULL,<br />
    status varchar(30),<br />
    PRIMARY KEY (order_id)<br />
) ENGINE=InnoDB; </code></p>
<p><strong>Add Foreign Key</strong></p>
<p><code>ALTER TABLE test_order<br />
ADD CONSTRAINT FK_test_order<br />
FOREIGN KEY (customer_id) REFERENCES test_customer(customer_id)<br />
ON UPDATE CASCADE<br />
ON DELETE CASCADE; </code></p>
<p><strong>Alternative way</strong></p>
<p>Alternatively we can directly add Foreign Key at the time of table creation. You may choose any one way (the following way or the way above) for creating tables and assigning foreign key.</p>
<p><code>SET foreign_key_checks = 0;</p>
<p>CREATE TABLE test_customer (<br />
    customer_id int(10) unsigned NOT NULL auto_increment,<br />
    name varchar(100),<br />
    address varchar(100),<br />
    PRIMARY KEY (customer_id)<br />
) ENGINE=InnoDB;</p>
<p>CREATE TABLE test_order (<br />
    order_id int(10) unsigned NOT NULL auto_increment,<br />
    customer_id int(10) unsigned NOT NULL,<br />
    status varchar(30),<br />
    PRIMARY KEY (order_id),<br />
	CONSTRAINT FK_test_order<br />
	FOREIGN KEY (customer_id) REFERENCES test_customer(customer_id)<br />
	ON UPDATE CASCADE ON DELETE CASCADE<br />
) ENGINE=InnoDB; </p>
<p>SET foreign_key_checks = 1;</code></p>
<p><strong>Insert sample data to test_customer and test_order tables</strong></p>
<p><code>INSERT INTO  test_customer<br />
(  customer_id ,  name ,  address )<br />
VALUES<br />
( '1',  'John',  'New York' ),<br />
( '2',  'Tom',  'London' );</p>
<p>INSERT INTO  test_order<br />
(  order_id ,  customer_id ,  status )<br />
VALUES<br />
( '1',  '1',  'pending' ),<br />
( '2',  '1',  'processing' ),<br />
( '3',  '2',  'complete' ),<br />
( '4',  '2',  'pending' );</code></p>
<p><strong>Doing UPDATE CASCADE</strong></p>
<p>When we update customer_id in test_customer (parent table), the customer_id field in test_order (child table) will also get updated.</p>
<p><code>UPDATE test_customer SET customer_id = 3 WHERE customer_id = 1;</code></p>
<p><strong>Note</strong>:- </p>
<p>We <strong>CANNOT </strong>directly update the foreign key in child table. </p>
<p>Doing this will result in error saying &#8220;<em>Cannot add or update a child row: a foreign key constraint fails</em>&#8220;.</p>
<p><code>UPDATE test_order SET customer_id = 4 WHERE customer_id = 3;</code></p>
<p><strong>Doing DELETE CASCADE</strong></p>
<p>When we delete customer_id in test_customer (parent table), the customer_id field in test_order (child table) will also get deleted.</p>
<p><code>DELETE FROM test_customer WHERE customer_id = 2;</code></p>
<p><strong>Note</strong>:-</p>
<p>We <strong>CAN </strong>directly delete rows from test_order (child table) like below:-</p>
<p><code>DELETE FROM test_order WHERE customer_id = 3;</code></p>
<p>Hope this helps. Thanks</p>
<p><strong>References</strong>:-<br />
1. <a target="_blank" rel="nofollow" href="http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html">http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html</a><br />
2. <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Foreign_key">http://en.wikipedia.org/wiki/Foreign_key</a></p>
<hr /><small>Copyright &copy; 2011<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:<br /> )</small><img src="http://blog.chapagain.com.np/?ak_action=api_record_view&id=1262&type=feed" alt="" />

<p><strong>Related posts:</strong><ol><li><a href='http://blog.chapagain.com.np/alter-mysql-table-to-add-drop-column-add-foreign-key/' rel='bookmark' title='Permanent Link: Alter MySQL table to add &#038; drop column &#038; add Foreign Key'>Alter MySQL table to add &#038; drop column &#038; add Foreign Key</a></li>
<li><a href='http://blog.chapagain.com.np/very-useful-sql-queries-with-joins/' rel='bookmark' title='Permanent Link: 10 Very Useful SQL Queries with JOINS'>10 Very Useful SQL Queries with JOINS</a></li>
<li><a href='http://blog.chapagain.com.np/backup-and-recovery-of-mysql-database/' rel='bookmark' title='Permanent Link: Backup and Recovery of MySQL database'>Backup and Recovery of MySQL database</a></li>
<li><a href='http://blog.chapagain.com.np/sql-error-cannot-insert-the-value-null-into-column-column-does-not-allow-nulls-insert-fails/' rel='bookmark' title='Permanent Link: SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.'>SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.</a></li>
<li><a href='http://blog.chapagain.com.np/magento-how-to-delete-system-attribute/' rel='bookmark' title='Permanent Link: Magento: How to delete System Attribute?'>Magento: How to delete System Attribute?</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.chapagain.com.np/mysql-database-foreign-key-understanding-and-implementation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Magento: Set Random Order in Collection using RAND()</title>
		<link>http://blog.chapagain.com.np/magento-set-random-order-in-collection-using-rand/</link>
		<comments>http://blog.chapagain.com.np/magento-set-random-order-in-collection-using-rand/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 12:09:38 +0000</pubDate>
		<dc:creator>Mukesh</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[order]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[rand]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://blog.chapagain.com.np/?p=845</guid>
		<description><![CDATA[Scenario: You have created a custom module. You have entered certain data in your database. You need to show the data randomly. Solution: In MySQL the rand() function helps the select query to fetch data randomly. In Magento, you can select random rows from MySQL table using Zend_Db_Expr(&#8216;RAND()&#8217;). You have to create a new function [...]


<strong>Related posts:</strong><ol><li><a href='http://blog.chapagain.com.np/generating-random-image/' rel='bookmark' title='Permanent Link: Generating random image'>Generating random image</a></li>
<li><a href='http://blog.chapagain.com.np/random-number-string-generation-in-php/' rel='bookmark' title='Permanent Link: Random number, string generation in PHP'>Random number, string generation in PHP</a></li>
<li><a href='http://blog.chapagain.com.np/magento-collection-functions/' rel='bookmark' title='Permanent Link: Magento: Very Useful Collection Functions'>Magento: Very Useful Collection Functions</a></li>
<li><a href='http://blog.chapagain.com.np/php-generating-random-string/' rel='bookmark' title='Permanent Link: PHP: Generating Multiple Random String'>PHP: Generating Multiple Random String</a></li>
<li><a href='http://blog.chapagain.com.np/magento-how-to-filter-product-collection-using-2-or-more-category-filters/' rel='bookmark' title='Permanent Link: Magento: How to filter product collection using 2 or more category filters?'>Magento: How to filter product collection using 2 or more category filters?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><strong>Scenario:</strong></p>
<p>You have created a custom module.<br />
You have entered certain data in your database.<br />
You need to show the data randomly.</p>
<p><strong>Solution:</strong></p>
<p><span id="more-845"></span></p>
<p>In MySQL the rand() function helps the select query to fetch data randomly. In Magento, you can select random rows from MySQL table using <strong>Zend_Db_Expr(&#8216;RAND()&#8217;)</strong>.</p>
<p>You have to create a new function in your module&#8217;s collection class <strong>(YourNamespace/YourModule/Model/Mysql4/YourModule/Collection.php)</strong></p>
<pre class="brush: php; title: ; notranslate">
public function setRandomOrder()
{
	$this-&gt;getSelect()-&gt;order(new Zend_Db_Expr('RAND()'));
	return $this;
}
</pre>
<p>Now, you can fetch random data from your table using the above create <strong>setRandomOrder</strong> function. The code below can be kept in the block or template (.phtml) file of your module.</p>
<pre class="brush: php; title: ; notranslate">
$collection = Mage::getModel('yourmodule/yourmodule')
					-&gt;getCollection()
					-&gt;setRandomOrder();

echo &quot;&lt;pre&gt;&quot;; print_r($collection-&gt;getData()); echo &quot;&lt;/pre&gt;&quot;;
</pre>
<p>Hope this helps. Thanks.</p>
<hr /><small>Copyright &copy; 2011<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:<br /> )</small><img src="http://blog.chapagain.com.np/?ak_action=api_record_view&id=845&type=feed" alt="" />

<p><strong>Related posts:</strong><ol><li><a href='http://blog.chapagain.com.np/generating-random-image/' rel='bookmark' title='Permanent Link: Generating random image'>Generating random image</a></li>
<li><a href='http://blog.chapagain.com.np/random-number-string-generation-in-php/' rel='bookmark' title='Permanent Link: Random number, string generation in PHP'>Random number, string generation in PHP</a></li>
<li><a href='http://blog.chapagain.com.np/magento-collection-functions/' rel='bookmark' title='Permanent Link: Magento: Very Useful Collection Functions'>Magento: Very Useful Collection Functions</a></li>
<li><a href='http://blog.chapagain.com.np/php-generating-random-string/' rel='bookmark' title='Permanent Link: PHP: Generating Multiple Random String'>PHP: Generating Multiple Random String</a></li>
<li><a href='http://blog.chapagain.com.np/magento-how-to-filter-product-collection-using-2-or-more-category-filters/' rel='bookmark' title='Permanent Link: Magento: How to filter product collection using 2 or more category filters?'>Magento: How to filter product collection using 2 or more category filters?</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.chapagain.com.np/magento-set-random-order-in-collection-using-rand/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>10 Very Useful SQL Queries with JOINS</title>
		<link>http://blog.chapagain.com.np/very-useful-sql-queries-with-joins/</link>
		<comments>http://blog.chapagain.com.np/very-useful-sql-queries-with-joins/#comments</comments>
		<pubDate>Fri, 14 May 2010 19:30:10 +0000</pubDate>
		<dc:creator>Mukesh</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[join]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[table]]></category>

		<guid isPermaLink="false">http://blog.chapagain.com.np/?p=779</guid>
		<description><![CDATA[The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. [@via w3schools] A SQL JOIN clause combines records from two or more tables in a database. It creates a set that can be saved as a table or [...]


<strong>Related posts:</strong><ol><li><a href='http://blog.chapagain.com.np/magento-join-filter-select-and-sort-attributes-fields-and-tables/' rel='bookmark' title='Permanent Link: Magento: Join, filter, select and sort attributes, fields and tables'>Magento: Join, filter, select and sort attributes, fields and tables</a></li>
<li><a href='http://blog.chapagain.com.np/alter-mysql-table-to-add-drop-column-add-foreign-key/' rel='bookmark' title='Permanent Link: Alter MySQL table to add &#038; drop column &#038; add Foreign Key'>Alter MySQL table to add &#038; drop column &#038; add Foreign Key</a></li>
<li><a href='http://blog.chapagain.com.np/mysql-database-foreign-key-understanding-and-implementation/' rel='bookmark' title='Permanent Link: MySQL Database: Foreign Key Understanding and Implementation'>MySQL Database: Foreign Key Understanding and Implementation</a></li>
<li><a href='http://blog.chapagain.com.np/fun-with-strings-in-php-part-1/' rel='bookmark' title='Permanent Link: Fun with strings in PHP (Part 1)'>Fun with strings in PHP (Part 1)</a></li>
<li><a href='http://blog.chapagain.com.np/sql-error-cannot-insert-the-value-null-into-column-column-does-not-allow-nulls-insert-fails/' rel='bookmark' title='Permanent Link: SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.'>SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<blockquote><p>The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. [@via w3schools]</p></blockquote>
<blockquote><p>A SQL JOIN clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as is. A JOIN is a means for combining fields from two tables by using values common to each. ANSI standard SQL specifies four types of JOINs: INNER, OUTER, LEFT, and RIGHT. In special cases, a table (base table, view, or joined table) can JOIN to itself in a self-join. [@via wikipedia]</p></blockquote>
<p><span id="more-779"></span></p>
<p>SQL Joins are helpful when we have to fetch data with a single query from two or more database tables.</p>
<p><strong>Case:</strong></p>
<p>I need to store news/article information. The news can also have comments and tags. News can be submitted/posted by multiple users.</p>
<p>According to the above scenario, I have created 5 tables and inserted some data into them :-</p>
<p><strong>news </strong>- to store news<br />
<strong>comments </strong>- to store comments for any particular news<br />
<strong>tags </strong>- to store tags associated with any particular news<br />
<strong>users </strong>- to store user information<br />
<strong>tags_news</strong> &#8211; to store relationship between news and tags</p>
<p>&#8211;<br />
&#8211; <strong>Table structure for table `comments`</strong><br />
&#8211;<br />
<code><br />
CREATE TABLE `comments` (<br />
  `id` bigint(20) NOT NULL auto_increment,<br />
  `news_id` bigint(20) NOT NULL,<br />
  `user_id` bigint(20) NOT NULL,<br />
  `detail` text NOT NULL,<br />
  `status` tinyint(1) NOT NULL default '1',<br />
  `comment_date` int(11) NOT NULL,<br />
  PRIMARY KEY  (`id`),<br />
  KEY `user_id` (`user_id`),<br />
  KEY `news_id` (`news_id`)<br />
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;<br />
</code></p>
<p>&#8211;<br />
&#8211; <strong>Dumping data for table `comments`</strong><br />
&#8211;<br />
<code><br />
INSERT INTO `comments` (`id`, `news_id`, `user_id`, `detail`, `status`, `comment_date`) VALUES<br />
(1, 1, 2, 'nice post :)', 1, 1273431296),<br />
(2, 2, 2, 'hahaha', 1, 1273431420),<br />
(3, 3, 2, '3123123', 1, 1273431452),<br />
(4, 1, 2, 'thank You', 1, 1273431475),<br />
(5, 2, 1, 'congratulations!', 1, 1273431500);<br />
</code><br />
&#8211; &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>&#8211;<br />
&#8211; <strong>Table structure for table `news`</strong><br />
&#8211;<br />
<code><br />
CREATE TABLE `news` (<br />
  `id` bigint(20) NOT NULL auto_increment,<br />
  `user_id` bigint(20) NOT NULL,<br />
  `title` text NOT NULL,<br />
  `detail` text NOT NULL,<br />
  `visit` int(11) NOT NULL default '0',<br />
  `status` tinyint(1) NOT NULL default '1',<br />
  `created_date` int(11) NOT NULL,<br />
  PRIMARY KEY  (`id`),<br />
  KEY `user_id` (`user_id`)<br />
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;<br />
</code><br />
&#8211;<br />
&#8211; <strong>Dumping data for table `news`</strong><br />
&#8211;<br />
<code><br />
INSERT INTO `news` (`id`, `user_id`, `title`, `detail`, `visit`, `status`, `created_date`) VALUES<br />
(1, 1, 'Extra Content', 'fasdfasdf', 2, 1, 1273431296),<br />
(2, 1, 'My My Question', 'this is jpt question.. :D', 16, 1, 1273431389),<br />
(3, 2, 'Am I ram?', 'I am ram..yahoo !!', 3, 1, 1273431420);<br />
</code><br />
&#8211; &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>&#8211;<br />
&#8211; <strong>Table structure for table `tags`</strong><br />
&#8211;<br />
<code><br />
CREATE TABLE `tags` (<br />
  `id` bigint(20) NOT NULL auto_increment,<br />
  `name` varchar(255) NOT NULL,<br />
  `slug` varchar(255) NOT NULL,<br />
  PRIMARY KEY  (`id`)<br />
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;<br />
</code><br />
&#8211;<br />
&#8211; <strong>Dumping data for table `tags`</strong><br />
&#8211;<br />
<code><br />
INSERT INTO `tags` (`id`, `name`, `slug`) VALUES<br />
(1, 'sagarmatha', 'sagarmatha'),<br />
(2, 'nepal', 'nepal'),<br />
(3, 'gautam buddha', 'gautam-buddha'),<br />
(4, 'testing', 'testing'),<br />
(5, 'tags', 'tags'),<br />
(6, 'tasty apple', 'tasty-apple'),<br />
(7, 'banana', 'banana');<br />
</code><br />
&#8211; &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>&#8211;<br />
&#8211; <strong>Table structure for table `tags_news`</strong><br />
&#8211;<br />
<code><br />
CREATE TABLE `tags_news` (<br />
  `id` bigint(20) NOT NULL auto_increment,<br />
  `news_id` bigint(20) NOT NULL,<br />
  `tags_id` bigint(20) NOT NULL,<br />
  PRIMARY KEY  (`id`),<br />
  KEY `news_id` (`news_id`)<br />
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;<br />
</code><br />
&#8211;<br />
&#8211; <strong>Dumping data for table `tags_news`</strong><br />
&#8211;<br />
<code><br />
INSERT INTO `tags_news` (`id`, `news_id`, `tags_id`) VALUES<br />
(1, 1, 1),<br />
(2, 1, 2),<br />
(3, 1, 3),<br />
(4, 2, 4),<br />
(5, 2, 5),<br />
(6, 2, 6),<br />
(7, 3, 6),<br />
(8, 3, 7);<br />
</code><br />
&#8211; &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>&#8211;<br />
&#8211; <strong>Table structure for table `users`</strong><br />
&#8211;<br />
<code><br />
CREATE TABLE `users` (<br />
  `id` bigint(20) NOT NULL auto_increment,<br />
  `user_id` bigint(20) NOT NULL,<br />
  `firstname` varchar(100) NOT NULL,<br />
  `lastname` varchar(100) NOT NULL,<br />
  PRIMARY KEY  (`id`),<br />
  KEY `user_id` (`user_id`)<br />
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;<br />
</code><br />
&#8211;<br />
&#8211; <strong>Dumping data for table `users`</strong><br />
&#8211;<br />
<code><br />
INSERT INTO `users` (`id`, `user_id`, `firstname`, `lastname`) VALUES<br />
(1, 1, 'Mukesh', 'Chapagain'),<br />
(2, 2, 'Christopher', 'Gayle'),<br />
(3, 3, 'Brian', 'Lara');<br />
</code><br />
&#8211; &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>Now, by using SQL JOINS, I can fetch data from these tables for different conditions and in different ways. Here follows the different SQL Queries with the magical JOIN statements:-</p>
<p><strong>1) SELECT NEWS WITH COMMENTS COUNT FOR EACH NEWS</strong></p>
<p><code><br />
SELECT n.*, ifnull(c.count,0) AS comment FROM news AS n<br />
	LEFT JOIN<br />
		(SELECT COUNT(comments.id) AS count, comments.news_id FROM comments GROUP BY comments.news_id) AS c<br />
			ON n.id = c.news_id<br />
				ORDER BY n.created_date DESC;<br />
</code>		</p>
<p><strong>2) SELECT NEWS POSTED BY ANY PARTICULAR USER (HERE, user_id = 1)</strong></p>
<p><code><br />
SELECT n.* FROM news AS n<br />
	INNER JOIN<br />
		users AS u<br />
			ON n.user_id = u.id<br />
				WHERE u.id = 1;<br />
</code></p>
<p><strong>3) SELECT NEWS POSTED BY ANY PARTICULAR USER (WITH USER&#8217;S FIRSTNAME AND LASTNAME) (HERE, user_id = 1)</strong></p>
<p><code><br />
SELECT n.*, u.firstname AS firstname, u.lastname AS lastname FROM news AS n<br />
	INNER JOIN<br />
		users AS u<br />
			ON n.user_id = u.id<br />
				WHERE u.id = 1;<br />
</code>			</p>
<p><strong>4) SELECT NEWS POSTED BY ANY PARTICULAR USER (WITH COMMENTS COUNT FOR EACH NEWS) (HERE, user_id = 1)</strong></p>
<p><code><br />
SELECT n.*, ifnull(c.count,0) AS comment, u.firstname AS firstname, u.lastname AS lastname FROM news AS n<br />
	LEFT JOIN<br />
		(SELECT COUNT(comments.id) AS count, comments.news_id FROM comments GROUP BY comments.news_id) AS c<br />
			ON n.id = c.news_id<br />
				INNER JOIN<br />
					users AS u<br />
						ON n.user_id = u.id<br />
							WHERE u.id = 1;<br />
</code></p>
<p><strong>5) SELECT COMMENTS FOR ANY PARTICULAR NEWS (HERE, news_id =1)</strong></p>
<p><code><br />
SELECT c.* FROM comments AS c<br />
	INNER JOIN<br />
		news AS n<br />
			ON c.news_id = n.id<br />
				WHERE c.news_id = 1;<br />
</code></p>
<p><strong>6) SELECT COMMENTS FOR ANY PARTICULAR NEWS (ALONG WITH USER INFORMATION) (HERE, news_id = 1)</strong></p>
<p><code><br />
SELECT c.*, u.firstname AS firstname, u.lastname AS lastname FROM comments AS c<br />
	INNER JOIN<br />
		news AS n<br />
			ON c.news_id = n.id<br />
				INNER JOIN<br />
					users AS u<br />
						ON c.user_id = u.id<br />
							WHERE c.news_id = 1;<br />
</code></p>
<p><strong>7) SELECT TAGS FOR ANY PARTICULAR NEWS (HERE, news_id = 1)</strong>	</p>
<p><code><br />
SELECT t.* FROM tags AS t<br />
	INNER JOIN<br />
		(SELECT tags_news.news_id AS news_id, tags_news.tags_id FROM tags_news WHERE tags_news.news_id = 1) AS tn<br />
			ON t.id = tn.tags_id;<br />
</code>			</p>
<p><strong>8) SELECT NEWS BY TAG NAME (HERE, tag = &#8216;nepal&#8217;)</strong></p>
<p><code><br />
SELECT n.*, t.name AS tag_name, t.slug AS tag_slug FROM news AS n<br />
	INNER JOIN<br />
		tags_news as tn<br />
			ON n.id = tn.news_id<br />
				INNER JOIN tags AS t<br />
					ON tn.tags_id = t.id<br />
						WHERE t.slug = 'nepal';<br />
</code>			</p>
<p><strong>9) SELECT NEWS BY TAG NAME (ALONG WITH COMMENTS COUNT) (HERE, tag = &#8216;nepal&#8217;)	</strong>		</p>
<p><code><br />
SELECT n.*, ifnull(c.count,0) AS comment, t.name AS tag_name, t.slug AS tag_slug, t.id AS tag_id FROM news AS n<br />
	INNER JOIN<br />
		tags_news AS tn<br />
			ON (n.id = tn.news_id)<br />
				INNER JOIN tags AS t<br />
					ON (tn.tags_id = t.id)<br />
						LEFT JOIN<br />
							(SELECT COUNT(comments.id) AS count, comments.news_id FROM comments<br />
								GROUP BY comments.news_id) AS c<br />
									ON n.id = c.news_id<br />
										WHERE t.slug = 'nepal'<br />
											ORDER BY n.created_date DESC;<br />
</code></p>
<p><strong>10) SELECT TAG CLOUD</strong>		</p>
<p><code><br />
SELECT t . * , IFNULL( tq.count, 0 ) AS count<br />
	FROM tags AS t<br />
		LEFT JOIN (<br />
			SELECT COUNT( tags_news.id ) AS count, tags_news.tags_id<br />
				FROM tags_news<br />
					GROUP BY tags_news.tags_id<br />
						) AS tq ON t.id = tq.tags_id<br />
							ORDER BY t.name ASC<br />
								LIMIT 15;<br />
</code><br />
Hope this helps. And thanks for reading.  </p>
<hr /><small>Copyright &copy; 2011<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:<br /> )</small><img src="http://blog.chapagain.com.np/?ak_action=api_record_view&id=779&type=feed" alt="" />

<p><strong>Related posts:</strong><ol><li><a href='http://blog.chapagain.com.np/magento-join-filter-select-and-sort-attributes-fields-and-tables/' rel='bookmark' title='Permanent Link: Magento: Join, filter, select and sort attributes, fields and tables'>Magento: Join, filter, select and sort attributes, fields and tables</a></li>
<li><a href='http://blog.chapagain.com.np/alter-mysql-table-to-add-drop-column-add-foreign-key/' rel='bookmark' title='Permanent Link: Alter MySQL table to add &#038; drop column &#038; add Foreign Key'>Alter MySQL table to add &#038; drop column &#038; add Foreign Key</a></li>
<li><a href='http://blog.chapagain.com.np/mysql-database-foreign-key-understanding-and-implementation/' rel='bookmark' title='Permanent Link: MySQL Database: Foreign Key Understanding and Implementation'>MySQL Database: Foreign Key Understanding and Implementation</a></li>
<li><a href='http://blog.chapagain.com.np/fun-with-strings-in-php-part-1/' rel='bookmark' title='Permanent Link: Fun with strings in PHP (Part 1)'>Fun with strings in PHP (Part 1)</a></li>
<li><a href='http://blog.chapagain.com.np/sql-error-cannot-insert-the-value-null-into-column-column-does-not-allow-nulls-insert-fails/' rel='bookmark' title='Permanent Link: SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.'>SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.chapagain.com.np/very-useful-sql-queries-with-joins/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SQL Error: Cannot insert the value NULL into column&#8230; column does not allow nulls. INSERT fails.</title>
		<link>http://blog.chapagain.com.np/sql-error-cannot-insert-the-value-null-into-column-column-does-not-allow-nulls-insert-fails/</link>
		<comments>http://blog.chapagain.com.np/sql-error-cannot-insert-the-value-null-into-column-column-does-not-allow-nulls-insert-fails/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 11:20:19 +0000</pubDate>
		<dc:creator>Mukesh</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[ms-sql]]></category>
		<category><![CDATA[problem]]></category>
		<category><![CDATA[query]]></category>

		<guid isPermaLink="false">http://blog.chapagain.com.np/?p=107</guid>
		<description><![CDATA[Error description: Cannot insert the value NULL into column &#8216;SourceId&#8217;, table &#8216;Advisory.dbo.AdvDocSource&#8217;; column does not allow nulls. INSERT fails. The statement has been terminated. The &#8216;CompanyAdd&#8217; procedure attempted to return a status of NULL, which is not allowed. A status of 0 will be returned instead. &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;- This error occurs because the &#8216;SourceId&#8217; column in [...]


<strong>Related posts:</strong><ol><li><a href='http://blog.chapagain.com.np/alter-mysql-table-to-add-drop-column-add-foreign-key/' rel='bookmark' title='Permanent Link: Alter MySQL table to add &#038; drop column &#038; add Foreign Key'>Alter MySQL table to add &#038; drop column &#038; add Foreign Key</a></li>
<li><a href='http://blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/' rel='bookmark' title='Permanent Link: Magento: How to select, insert, update, and delete data?'>Magento: How to select, insert, update, and delete data?</a></li>
<li><a href='http://blog.chapagain.com.np/very-useful-sql-queries-with-joins/' rel='bookmark' title='Permanent Link: 10 Very Useful SQL Queries with JOINS'>10 Very Useful SQL Queries with JOINS</a></li>
<li><a href='http://blog.chapagain.com.np/mysql-database-foreign-key-understanding-and-implementation/' rel='bookmark' title='Permanent Link: MySQL Database: Foreign Key Understanding and Implementation'>MySQL Database: Foreign Key Understanding and Implementation</a></li>
<li><a href='http://blog.chapagain.com.np/displaying-all-products-and-new-products-listing-in-columngrid-layout-zen-cart/' rel='bookmark' title='Permanent Link: Displaying all products and new products listing in column/grid layout &#8211; Zen-cart'>Displaying all products and new products listing in column/grid layout &#8211; Zen-cart</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Error description:</p>
<p style="text-align: justify;">Cannot insert the value NULL into column &#8216;SourceId&#8217;, table &#8216;Advisory.dbo.AdvDocSource&#8217;; column does not allow nulls. INSERT fails.<br />
The statement has been terminated. The &#8216;CompanyAdd&#8217; procedure attempted to return a status of NULL, which is not allowed. A status of 0 will be returned instead.<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p style="text-align: justify;">This error occurs because the &#8216;SourceId&#8217; column in my table is primary key and it is set to not null. i.e. it doesn&#8217;t allow null entries. And I have not made it auto increment.</p>
<p><span id="more-107"></span></p>
<p>For making a table column auto increment:<br />
- Go to server explorer.<br />
- In Column Properties, go to Identity Specification.<br />
- Go to (Is Identity) and make it &#8216;Yes&#8217; from the selection list.</p>
<p>You are done. You also have the option for Identity Increment and Identity Seed.</p>
<p>The SQL Query is:<br />
CREATE TABLE [yourTableName](SourceID int IDENTITY(1,1) NOT NULL, &#8230;</p>
<hr /><small>Copyright &copy; 2011<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:<br /> )</small><img src="http://blog.chapagain.com.np/?ak_action=api_record_view&id=107&type=feed" alt="" />

<p><strong>Related posts:</strong><ol><li><a href='http://blog.chapagain.com.np/alter-mysql-table-to-add-drop-column-add-foreign-key/' rel='bookmark' title='Permanent Link: Alter MySQL table to add &#038; drop column &#038; add Foreign Key'>Alter MySQL table to add &#038; drop column &#038; add Foreign Key</a></li>
<li><a href='http://blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/' rel='bookmark' title='Permanent Link: Magento: How to select, insert, update, and delete data?'>Magento: How to select, insert, update, and delete data?</a></li>
<li><a href='http://blog.chapagain.com.np/very-useful-sql-queries-with-joins/' rel='bookmark' title='Permanent Link: 10 Very Useful SQL Queries with JOINS'>10 Very Useful SQL Queries with JOINS</a></li>
<li><a href='http://blog.chapagain.com.np/mysql-database-foreign-key-understanding-and-implementation/' rel='bookmark' title='Permanent Link: MySQL Database: Foreign Key Understanding and Implementation'>MySQL Database: Foreign Key Understanding and Implementation</a></li>
<li><a href='http://blog.chapagain.com.np/displaying-all-products-and-new-products-listing-in-columngrid-layout-zen-cart/' rel='bookmark' title='Permanent Link: Displaying all products and new products listing in column/grid layout &#8211; Zen-cart'>Displaying all products and new products listing in column/grid layout &#8211; Zen-cart</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.chapagain.com.np/sql-error-cannot-insert-the-value-null-into-column-column-does-not-allow-nulls-insert-fails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->
