...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

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

  Receive Our Newsletter

PHP and mySQL picture



Questions about PHP and mySQL:

Ask question

More Articles:
How to succeed online
How to remember passwords with ease
How to copy files quickly