-1

My table structures are :

table1 :

id      |    title    |    category    | body
--------+-------------+----------------+---------------
1       | blah blah   | 2              | blah blah blah
2       | blah blah   | 3              | blah blah blah
3       | blah blah   | 2              | blah blah blah
4       | blah blah   | 1              | blah blah blah

table2 :

id      |   cid    |   type    |     link
--------+----------+-----------+--------------------
1       | 1        | c1        | http://........
1       | 2        | c1        | http://........
1       | 3        | c1        | http://........
1       | 4        | c1        | http://........
1       | 2        | c2        | http://........
1       | 3        | c2        | http://........
1       | 1        | c2        | http://........

Now I use this code to select from this tables in 3 separate queries :

$query = mysql_select("SELECT * FROM table1");
while ($result = mysql_fetch_array($query)) {
   $c1 = mysql_fetch_array(mysql_query("SELECT link FROM table2 WHERE cid=".$result['id']." AND type = 'c1' ORDER BY id DESC LIMIT 1"));
   $c2 = mysql_fetch_array(mysql_query("SELECT link FROM table2 WHERE cid=".$result['category']." AND type = 'c2' ORDER BY id DESC LIMIT 1"));

  ....
}

Is it possible to write these queries in one query for mysql ?

MajAfy
  • 3,007
  • 10
  • 47
  • 83

1 Answers1

0
SELECT * FROM table1 a
LEFT JOIN table2 b ON b.cid = a.id AND type = 'c1'
LEFT JOIN table2 c ON b.cid = a.category AND type = 'c2'
ORDER BY a.title ASC, b.id DESC, c.id DESC

maybe expanded with an ORDER BY.

You could also try INNER JOIN instead, if you only want to get those rows of table1, which have the requested rows in table2.

Ulrich Thomas Gabor
  • 6,584
  • 4
  • 27
  • 41