如何在SQL查询中将子表声明为父表?

时间:2019-09-07 09:30:29

标签: php mysql left-join inner-join parent-child

我正在搜索页面上,我必须加入总共5张桌子。

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

问题是,我的查询无法从Table two获取数据 我的查询是

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";

我认为Table two中没有Table one的任何字段,这就是为什么我的查询没有从Table two获取数据的原因 我说的对吗?

Table one是父表,所有其他表都是子表。对? 我的想法是,如果我可以让Table two成为另一个父母,而Table three是孩子,也许我的查询会起作用。

我正在寻找一个查询,什么可以从所有表中获取所有数据。列是否为空。 希望你们能理解。如果没有,请告诉我,谢谢。

1 个答案:

答案 0 :(得分:0)

我解决了。 :) 这是我的新查询-

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

我不知道这是否是编写此查询的正确方法,但它确实有效。