Karem
Karem

Reputation: 18103

PHP: Search in more tables at once?

How do i make a mysql query for more tables to check at once? i mean, something like:

$sql = mysql_query("SELECT username FROM table1, table2, table3 WHERE username = '$username'");
$numer = mysql_num_rows($sql);
echo "You have ".$number;

can you do like this?

What i want to do is to show a user all his posts from the whole site..

Upvotes: 4

Views: 158

Answers (3)

Sarfraz
Sarfraz

Reputation: 382746

You can use the SQL union keyword for that. It is used to union the tables and get the desired data out of them.

Upvotes: 0

Bjoern
Bjoern

Reputation: 16304

You could do with a UNION.

Change the Select-Statement in your mysql_query to...

SELECT username FROM table1 WHERE username = '$username'
UNION
SELECT username FROM table2 WHERE username = '$username'
UNION
SELECT username FROM table3 WHERE username = '$username'

Upvotes: 1

The Scrum Meister
The Scrum Meister

Reputation: 30111

In the query you provided, its using a full outer-join. Use union selects instead.

SELECT username FROM table1 WHERE username = '$username'
UNION SELECT username FROM table2 WHERE username = '$username'
UNION SELECT username FROM table3 WHERE username = '$username'

Upvotes: 3

Related Questions