문제

Using CodeIgniter Active Records:

    $country = $_SESSION['search'];
    $min_price = $_SESSION['min_price'];
    $max_price = $_SESSION['max_price'];
    $condition = "";
    $this->db->select('*,attachments.title as image');
    $this->db->from('details');
    $this->db->join('attachments', 'attachments.parent = details.id');
    $this->db->where('attachments.type', 'quotes');
    if ($country != '')
        {
        $condition .= "(details.service_location IN ('" . $country . "') OR details.country in ('" . $country . "'))";

        $this->db->where($condition);
        }

        $this->db->where('details.price_range_from >=', $min_price);
        $this->db->where('details.price_range_to <=', $max_price);


    $this->db->group_by("attachments.parent");
    $this->db->order_by("details.created_on", "asc");
    $query = $this->db->get();
    $result = $query->result();
    return $result;
    }

I have 2 tables say details and attachments, and I want to do a join on them.

Table details will always have records in it.

When table attachments has rows in it, I want the query to turn all the rows in which table details and table attachments matches. (i.e. behave like inner join)

However, if table attachments is empty, I'd like to return everything from table details.

and also checking table attachments in where condition.

Is this possible to do in 1 query?

Thanks.

도움이 되었습니까?

해결책

Use LEFT OUTER JOIN rather than JOIN

FROM (details) 
LEFT OUTER JOIN attachments ON attachments.parent = details.restaurant_id 

UPDATE

and of course

GROUP BY details.restaurant_id

rather than attachments.parent

다른 팁

Although I think it's a bit weird requirement, the principal structure you can use is:

inner join union select *, ... from details where 0 = (select count(*) from attachments where ...)

If the inner join doesn't return rows, the second query will return all details. If the inner join returns rows, the second query won't return anything because attachments are found (count(*) returns some positive value).

I think you can fill in the details yourself. I don't guarantee for brilliant performance.

Use two different queries, check if attachments has rows and run query with inner join details else return rows from details table

 IF EXISTS (SELECT * FROM @attachments where column1='')
   BEGIN
  SELECT * FROM attachments as atc 
  INNER JOIN details AS det ON   atc.parent = det.restaurant_id where column2=''
END
ELSE
  SELECT * FROM details  where column2=''
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top