phpmysqlcodeigniterjoinmysql-variables

Rownum in sql INNER JOIN?


I want use rownum in following query select, i use of it true in following first query but don't know how should use from it in following second query?

First query that work true:

$this -> db -> query("
SELECT @rownum := @rownum + 1 rownum, 
       t.* 
FROM   (SELECT * 
        FROM   table 
        ORDER  BY id DESC 
        LIMIT  $offset, $coun) t, 
       (SELECT @rownum := 0) r 
")

I echo above rownum in html code on foreach as: echo intval($row -> rownum + $offset)

Second query(i want use from it in this query, how is for this query?):

$this -> db -> query("
SELECT tour_foreign.id, 
       tour_foreign.name, 
       tour_foreign_residence.name_re, 
       tour_foreign.service, 
       tour_foreign.date_go, 
       tour_foreign.date_back, 
       tour_foreign.term 
FROM   tour_foreign 
       INNER JOIN tour_foreign_residence 
         ON ( tour_foreign.id = tour_foreign_residence.relation ) 
WHERE  tour_foreign.name LIKE "%' . $find . '%" 
        OR tour_foreign_residence.name_re LIKE "%' . $find . '%"
")

Solution

  • Try this, simply adding the @rownum to the start of the SELECT list and the @rownum reset as an implicit JOIN onto the end. I tested this against one of my databases with a similar JOIN and it appears to work correctly.

    It looks peculiar to mix explicit JOINs with the implicit join against the @rownum reset pseudotable, but I don't know of a way to perform an explicit JOIN there when there is no common column. If anyone can improve that situation, please comment.

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

    UPDATE an explicit JOIN without an ON clause also works:

    FROM   tour_foreign 
           INNER JOIN tour_foreign_residence 
             ON ( tour_foreign.id = tour_foreign_residence.relation )
           JOIN (SELECT @rownum := 0) r