user2594383
user2594383

Reputation: 57

Selecting multiple tables from database

I am trying to make my php code to read off of two tables in my database. Like if it does not exist in one table it will check the other and see.

$mystyle = mysql_query("SELECT * FROM images WHERE `name` = '$name'"); 

How would I make it read from the table images and the table images_2

I tried doing this: [but didn't work of course]

$mystyle = mysql_query("SELECT * FROM images, images_2 WHERE `name` = '$name'"); 

Upvotes: 0

Views: 62

Answers (3)

Krish R
Krish R

Reputation: 22711

You can use UNION ,

(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1)
 UNION
(SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col;

http://dev.mysql.com/doc/refman/5.0/en/union.html

Upvotes: 0

Mike
Mike

Reputation: 2559

I think you will have to return a count of the rows from the SELECT on images and if zero then run the SELECT against images_2

Upvotes: 0

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79929

Use UNION(implicit distinct) or UNION ALL :

SELECT * FROM images WHERE `name` = '$name'
UNION ALL
SELECT * FROM images_2 WHERE `name` = '$name'

Assuming images and images_2 has the same table structure, otherwise you have to list the columns' names explicitly instead of SELECT *.


Note that: Use PDO instead of Mysql_* functions, it is deprecated and vulnerable to SQL Injection.

Upvotes: 5

Related Questions