简体   繁体   中英

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'"); 

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 .

我认为您将必须从图像上的SELECT返回行数,如果为零,则对images_2运行SELECT

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM