Combining several database table together?

2020-02-07 13:19发布

问题:

I have two tables tour_foreign&tour_foreign_residence in database and want merger this two table together that get output from PHP code as following example:

My tables and values it:

I want get as output tour_foreign.id = tour_foreign_residence.relation :

One-week tour of Istanbul_1 | 88888 & 99999 $ 112233 $ 445566 | Three nights and two days | 15:29
One-week tour of Istanbul_2 | 55555 & 66666 $ 77777 | Three nights and two days | 12:03
One-week tour of Istanbul_3 | 11111 & 22222 $ 33333 $ 44444 | Three nights and two days | 12:03

My try is this but it don't give to me what that I want in above:

$this -> db -> query("
    SELECT
           @rownum := @rownum + 1 rownum,
           tour_foreign.id, 
           tour_foreign.name, 
           tour_foreign_residence.name_re,  
           tour_foreign.term,
           tour_foreign.time_go, 
           tour_foreign.time_back,
           tour_foreign.type_of_vehicle
    FROM   tour_foreign 
           INNER JOIN tour_foreign_residence 
             ON ( tour_foreign.id = tour_foreign_residence.relation )
           JOIN (SELECT @rownum := 0) r
    WHERE  tour_foreign.name LIKE "%' . $find . '%" 
            OR tour_foreign_residence.name_re LIKE "%' . $find . '%"    
")

How can fix it?

回答1:

Try using GROUP_CONCAT() to join the names from you tour_foreign_residence table



回答2:

Not sure why you are joining on @rownum, it might be messing with your result set. Try taking it out and see if it works.

Your inner join looks ok, except I have never seen it with the wrapped parens, but I suspect it will work as expected. To test your query you could remove the complicated where clause and just put something like where tour_foreign.id = 1.

Something like:

SELECT
    tf.*
FROM 
    tour_foreign AS tf
INNER JOIN
    tour_foreign_residence AS tfr
ON
    tfr.relation = tf.id
WHERE
    tf.id = 1

I implemented aliases for your longer table names (tf, and tfr) as they are easier to work with.