简体   繁体   中英

Mysql join to display only unique ids

I am trying to use an sql query but i get multiple times the same result.

I read that i have to use an INNER JOIN or a LEFT JOIN to avoid that. The only problem is that i am a bit newbie with mysql so i can't actually make a successful query.

The query is this

SELECT * 
FROM table1,table2 
WHERE table1.name LIKE '%$str%' 
OR 
table1.last_name LIKE '%$str%'

$str is a string that i pass in a php function in order to make a search.

You need to make a join between those two tables.

SELECT * 
FROM table1
INNER JOIN table2
   ON table1.key = table2.key
WHERE table1.name LIKE '%$str%' 
OR 
table1.last_name LIKE '$str%'

You should also protect against SQL injection by using mysql_real_escape_string .

$query = "SELECT * 
FROM table1
INNER JOIN table2
   ON table1.key = table2.key
WHERE table1.name LIKE '%" . mysql_real_escape_string($str) ."%' 
OR 
table1.last_name LIKE  '%" . mysql_real_escape_string($str) ."%'";

Here is the documentation on the escape string .

You could try:

SELECT DISTINCT t1,*, t2.* 
FROM table1 t1 INNER JOIN table2 t2
ON t1.id = t2.table1_id 
WHERE 
    table1.name LIKE '%$str%' OR 
    table1.last_name LIKE '%$str%'

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