简体   繁体   中英

How to select two record from two different table with one query in mysql

How to select two record from two different table with one query in mysql?

for a search query I'm using

$search = $_GET['gd']
$arama_sonuc = mysql_query("select * from mp3 where baslik like '%$search%'");

well it's ok. it shows me results from mp3 table. but with same query I need to search something on HABERLER table too.. how can I do?

Use the UNION command http://dev.mysql.com/doc/refman/5.0/en/union.html

select * from mp3 where baslik like '%$search%'
UNION 
select * from HABERLER where baslik like '%$search%'

(presumably they have the same number of columns and the same types, etc)

The question is unclear and you may either need one of the following constructs

SELECT *
FROM mp3
WHERE baslik like '%$search%'"
UNION
SELECT *
FROM HABERLER
WHERE baslik like '%$search%'"

or

SELECT * 
FROM mp3 M
JOIN HABERLER H on H.some_field = M.some_field_in_mp3_table
WHERE baslik like '%$search%'"

The UNION construct allows one to collect in a single result set records from different tables; the records need to be structurally identical, ie have the same column (not necessarily named the same but with the same type of data). The result set includes all the rows that satisfy the first query and all the rows that satisfy the second query (with possible elimination of duplicates depending on the ALL keyword).
UNION is useful if for example mp3 and HABERLER table contain the same type of records (ex: info about music files).

The JOIN construct allows one to get a result set that contains records which are made from the columns in the first table and the columns made in the second table. The records from the second table are selected on the basis on their satifying the "ON condition" of the JOIN.
JOIN is useful if the two tables contain complementary information (for example mp3 contains info about mp3 files, and HABERLER contains info about musicians; mp3 makes reference to musicians in one of its columns and HABERLER has a column that identify musician by the same value)

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