简体   繁体   中英

How to declare a child table as parent table in a sql query?

I am working on a search page and there are total 5 table I have to join.

Table one   (fields) = id |   title  | country  | state
Table two   (fields) = id | category 
Table three (fields) = id | tbl_1_id | tbl_2_id | value
Table Four  (fields) = id | tbl_1_id | data
Table Five  (fields) = id | tbl_1_id | tags

The problem is, my query cannot fetch data from Table two My query is,

SELECT one.*, two.*, three.*, four.*, five.*

FROM one
LEFT JOIN two   ON two.id = three.tbl_2_id
LEFT JOIN three ON one.id = three.tbl_1_id
LEFT JOIN four  ON one.id = four.tbl_1_id
LEFT JOIN five  ON one.id = five.tbl_1_id

WHERE 

one.title    LIKE '%$keyword%' OR 
one.country  LIKE '%$keyword%' OR 
one.state    LIKE '%$keyword%' OR 
two.category LIKE '%$keyword%' OR 
three.value  LIKE '%$keyword%' OR 
four.data    LIKE '%$keyword%' OR 
five.tags    LIKE '%$keyword%' ORDER By one.id DESC";

I think, Table two don't have any field from Table one that is why my query not getting data from Table two Am I right?

Table one is the parent table and all other tables are child. Right? What I thought was, if I can make Table two another parent and Table three it's child, maybe my query will work.

I am looking for a query, what can get all data from all table. Whether the columns are empty or not. Hope you guys understand. If not, please let me know, Thanks.

I solved it. :) This is my new query -

SELECT one.*, two.*, three.*, four.*, five.*

FROM one 
LEFT JOIN two
    INNER JOIN three ON two.id = three.tbl_2_id
                     ON one.id = three.tbl_1_id
    LEFT JOIN four   ON one.id = four.tbl_1_id
    LEFT JOIN five   ON one.id = five.tbl_1_id

WHERE 

one.title    LIKE '%$keyword%' OR 
one.country  LIKE '%$keyword%' OR 
one.state    LIKE '%$keyword%' OR 
two.category LIKE '%$keyword%' OR 
three.value  LIKE '%$keyword%' OR 
four.data    LIKE '%$keyword%' OR 
five.tags    LIKE '%$keyword%' ORDER By one.id DESC

I don't know if it's the right way to write this query, but it worked.

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