tags:

views:

249

answers:

2

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

for a search query im using

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

well its 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? thanks...

+2  A: 

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)

mlathe
Parse error: syntax error, unexpected T_STRING error
Ronnie Chester Lynwood
@Ronnie Chester Lynwood: Are you using at least MySQL 5.0? If not, check whether UNION is supported in your version...
Jonathan Leffler
"unexpected T_STRING" is a PHP issue. Try running the query directly on MySQL. If that works then you're gold, but you just need to find out how to use it in PHP.
mlathe
+3  A: 

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, i.e. 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)

mjv
thank you so much
Ronnie Chester Lynwood