tags:

views:

55

answers:

3

and get meaningful results.

Currently I am running these three queries:

  SELECT t.type,t.id,s.title FROM db1.tags t INNER JOIN db1.st s ON s.id=t.id WHERE id LIKE '%%' AND t.tag='foo' AND t.type='s' ORDER BY tag desc LIMIT 0, 19
  SELECT t.type,t.id,v.title FROM db1.tags t INNER JOIN db1.vi v ON v.id=t.id WHERE id LIKE '%%' AND t.tag='foo' AND t.type='v' ORDER BY tag desc LIMIT 0, 19
  SELECT t.type,t.id,i.ca AS title FROM db1.tags t INNER JOIN db2.tablename i ON i.id=t.id WHERE id LIKE '%%' AND t.tag='foo' AND t.type='i' ORDER BY tag desc LIMIT 0, 19

then trying to combine the data results but what I would really prefer is if I could combine them into a single query.

Any thoughts?

+3  A: 

You can use UNION ALL:

SELECT * FROM (
    SELECT t.type,t.id,s.title
    FROM db1.tags t
    INNER JOIN db1.st s ON s.id=t.id
    WHERE id LIKE '%%' AND t.tag='foo' AND t.type='s'
    ORDER BY tag DESC
    LIMIT 0, 19
) AS T1
UNION ALL
SELECT * FROM (
    SELECT t.type,t.id,v.title
    FROM db1.tags t
    INNER JOIN db1.vi v ON v.id=t.id
    WHERE id LIKE '%%' AND t.tag='foo' AND t.type='v'
    ORDER BY tag DESC
    LIMIT 0, 19
) AS T2
UNION ALL
SELECT * FROM (
    SELECT t.type,t.id,i.ca AS title
    FROM db1.tags t
    INNER JOIN db2.tablename i ON i.id=t.id
    WHERE id LIKE '%%' AND t.tag='foo' AND t.type='i'
    ORDER BY tag DESC
    LIMIT 0, 19
) AS T3
ORDER BY type, id DESC
Mark Byers
I'd enclose it into the nested queries, though
Quassnoi
that'll do it thank you
mcgrailm
ohh I had to put () around each query and move the limit and order by to the end
mcgrailm
@mmcgrail: Yes sorry, you can't do an ORDER BY in a UNION ALL, I missed that. Glad you got it working. BTW, I've changed my comment to another alternative for the case where you want 19*3 rows rather than just 19. But if you want 19, then what you did already is fine.
Mark Byers
what i found is that the limit need to ot at the end with the order by and also that the order by needs to be column need to be one of the select columns i.e. type or id or title in this case thanks for your help
mcgrailm
A: 

you should consider using UNION. since you always return the 3 same fields type/id/title

this would also make 3 internal requests to the database , however, you will be able to limit the results and order the full aggregated result.

dweeves
A: 

If you don't want to use Unions you could try using outer joins. Add the t.type=something in the on clause. Finally you'd have to use a case statement to select the title. Not really easier than the Union approach but it might be faster since it would just be one call.

Peter