Help for a sql query

Post Reply
User avatar
Rksk
Major
Major
Posts: 730
Joined: Thu Jan 07, 2010 4:19 pm
Location: Rathnapura, Sri Lanka

Help for a sql query

Post by Rksk » Wed Sep 28, 2011 11:05 pm

Imagine there are two tables like below.

Table1:
user_iduser_namegroup_id
1neoadmin
2rkskpromo
3nipunapromo
4facepromo
5herathhelp
6samanuser
7magnetomod
8xuser
9yuser
.
.
.
Table2:
post_idtitletextuser_id
.
.
.
I want to select all the posts by all users who has the group_id "promo".
It can do by getting "promo" group members' ids from table1 and selecting all topics made by those ids from table2.

But when those tables being larger this can be a very slower way.

Please tell me a one sql query to do that.

(I'm using PHP & Mysql)
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: Help for a sql query

Post by Neo » Wed Sep 28, 2011 11:32 pm

Code: Select all

SELECT * FROM table1, table2 WHERE table1.user_id = tabled2.user_id AND group_id = 'promo';
The * after SELECT will add all fields to your query result which will slow down the operation. So make sure you only add the fields you need in the output.

For example, if you only need user_id, post_id and title,

Code: Select all

SELECT table1.user_id, post_id, title FROM table1, table2 WHERE table1.user_id = tabled2.user_id AND group_id = 'promo';
Note that it is required to use table name as a prefix when fields exists with the same name. If unique, no need to add the table name as a prefix.
User avatar
Rksk
Major
Major
Posts: 730
Joined: Thu Jan 07, 2010 4:19 pm
Location: Rathnapura, Sri Lanka

Re: Help for a sql query

Post by Rksk » Wed Sep 28, 2011 11:41 pm

thank you.
Post Reply

Return to “PHP & MySQL”