...Beauty, cleaning, DIY tips and more - free to join!
   Login   Contact us   Site map   Puzzle Club   Ask a question    Newsletter

How To Select The Same Field From Two Tables In One Query

Computing : Learning PHP

If you are using mySQL often then there are various scenarios you will come across at one time or other.

One of these will be wanting to collect the same field from two tables in one query.

For instance, imagine that in a forum the first post is stored in a separate table to the replies.

Both have a date_posted column.

Now if you want to find the latest post for a forum, you will need to sort in descending order limit 1 the Combined data from those two fields - as a new post may be the latest post or a reply to any existing post.

To do this easily, you can use the UNION query in mysql. Thus the relevant query here would be:

SELECT date_posted FROM newposts UNION SELECT date_posted FROM replies ORDER BY date_posted DESC LIMIT 1

You simply stitch the two calls to select with the keyword UNION in between (requires mySQL 4).


Profile image!
By: Stephen

  More about PHP and mySQL

  Reply to How To Select The Same Field From Two Tables In One Query

  Receive Our Newsletter

  Send to friend

PHP and mySQL picture



Questions about PHP and mySQL:

Ask question

More Articles:
How to get traffic to your blog
How to syndicate your content
How to play computer games and get fit