Reputation: 57
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
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
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
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