2013-05-28 1 views
-2

다른 데이터베이스 테이블에서 데이터를 검색하고 싶습니까?다른 데이터베이스 테이블에서 데이터를 검색하려면 어떻게합니까?

예를 들어, 'demo'와 같은 단어를 입력하고 'search'버튼을 누르면 'product'테이블과 'article'테이블의 'demo'단어와 관련된 데이터를 표시합니다.

그래서 어떻게 SQL 문을 작성합니까?

그건 그렇고, 나는 PHP와 MySQL을 사용합니다.

+0

당신도 처음 아무것도 검색나요 작동 방법을 알아 준 작은 코드? 뭔가 '좋아해?' –

+0

적어도 한번 시도하고 코드를 표시해야합니다 .. –

+3

코드뿐만 아니라 테이블 구조. –

답변

0

과 같은 쿼리로 시작할 수 있습니다. 테이블 구조, 열의 정보를 표시하지 않으므로 해당 사항이 적용되지 않습니다. 그래서 다음은 UNION ALL

SELECT * FROM article a 
a.article LIKE "%demo%" 

UNION ALL 

SELECT * FROM product p 
p.title LIKE "%demo%"; 

을 시도하지만 그들은 동일한 수의 열이 있어야한다고 확신 할 수 있습니다 내 추측

SELECT * FROM article a 
INNER JOIN product p 
ON p.id = a.product_id 
WHERE 
a.article LIKE "%demo%" 
OR 
p.title LIKE "%demo%"; 

입니다. 다음은

UNION here에 더 읽기입니다 내가 시작하고

<?php 
    mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error()); 
    /* 
     localhost - it's location of the mysql server, usually localhost 
     root - your username 
     third is your password 

     if connection fails it will stop loading the page and display an error 
    */ 

    mysql_select_db("your_database") or die(mysql_error()); 
    /* your_database is the name of database we've created */ 
?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Search results</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <link rel="stylesheet" type="text/css" href="style.css"/> 
</head> 
<body> 
<?php 
    $query = $_GET['query']; 
    // gets value sent over search form and in your case it is demo 

    $min_length = 3; 
    // you can set minimum length of the query if you want 

    if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then 

     $query = htmlspecialchars($query); 
     // changes characters used in html to their equivalents, for example: < to &gt; 

     $query = mysql_real_escape_string($query); 
     // makes sure nobody uses SQL injection 

     $raw_results = mysql_query("SELECT * FROM article a INNER JOIN product p 
        ON p.id = a.product_id WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error()); 

     // * means that it selects all fields, you can also write: `id`, `title`, `text` 
     // articles is the name of our table 

     // '%$query%' is what we're looking for, % means anything, for example if $query is Hello 
     // it will match "demo", "here demo", "demohere", if you want exact match use `title`='$query' 
     // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query' 

     if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following 

      while($results = mysql_fetch_array($raw_results)){ 
      // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop 

       echo "<p><h3>".$results['title']."</h3>".$results['text']."</p>"; 
       // posts results gotten from database(title and text) you can also show id ($results['id']) 
      } 

     } 
     else{ // if there is no matching rows do following 
      echo "No results"; 
     } 

    } 
    else{ // if query length is less than minimum 
     echo "Minimum length is ".$min_length; 
    } 
?> 
</body> 
</html> 
+0

답장을 보내 주셔서 감사합니다. 내 진짜 문제는 테이블 '제품'과 테이블 '기사'에 외래 키 연결이 없다는 것입니다. 그들은 이상적입니다. – user2089630

+0

그래서 문제는 위에 질문 한 것과 다릅니다. 이것은 데이터베이스 디자인이 좋지 않은 단순한 문제입니다. – Yogus

+0

@ user2089630 위의 UNION 개념을 읽으십시오. 대답을 받아들이고 투표가 효과가 있으면 투표하세요 : – Yogus

관련 문제