There is a cats table and a sales table.

sales stores offers (id, need, ican) , and cats (id, need, ican) description of offers (id, title) . sales in need and ican write the id values ​​from cats .

Cats:

 id| title ----------------- 1 | уборка дома 2 | ремонт машины 3 | мойка окон 

Sales:

 id|need|ican ------------ 1 | 2 | 1 2 | 3 | 3 3 | 1 | 3 

It is necessary to bring sales tied to it cats taking from there the title to need and ican.

We construct the query:

 SELECT sales.id AS sales_id, cats.title AS cats_title FROM sales, cats WHERE sales.need = cats.id AND sales.ican = cats.id 

In the end - empty, no answer.

The question is whether it is possible to output both need and ican with this one query, can use ican , is there a more efficient way?

    3 answers 3

    You use a join of tables, in which you ask that the id and need values ​​in the sales table should be the same, which is actually incorrect, therefore it will produce an empty string.

    Use two joins with tables:

     select s.id, c1.title need_title, c2.title ican_title from sales s join cats c1 on s.need = c1.id join cats c2 on s.ican = c2.id order by s.id 

    Sample on sqlfiddle with the answer .

    • In my opinion, I just lost my virginity in the mysql query compilation area :) - Andrew

    Do through left join

     SELECT sales.id AS sales_id, cat_need.title AS cats_need_title, cat_ican .title as cats_ican_title FROM sales left join cats cat_need on sales.need = cat_need.id left join cats cat_ican on sales.ican = cat_ican.id 

      LEFT JOIN is supposed to help

       SELECT A.id sales_id, B.aw_textad_id cats_title FROM sales A LEFT JOIN cats B ON A.sales.need = B.id WHERE A.ican = B.id