views:

43

answers:

3

Hello All,

I am trying to query 2 tables in a database, each query having nothing to do with each other, other then being on the same page.

Query 1 - The first query on the page will retrieve text and images that are found throughout the page from Table A.

Query 2 - The second query will retrieve several products with a image, description and title for each product from Table B.

I know that putting the second query inside the first query's while loop would work but of course is very inefficient.

How can I and what is the best way to retrieve all the data I need through 1 query?

Thanks,

  • Dane
+3  A: 

So all you want to know is if its ok to have 2 queries on the same webpage? Its A-OK. Go right ahead. Its completelly normal. No one expects a join between table news and table products. Its normal to usetwo queries to fetch data from two unrelated tables.

Iznogood
They are not related, so it's ok to have 2 querys on the same page?
teamdane
A: 

Use LEFT or INNER JOIN (depends on whether you want to display records from TableA that have no correspondent records in TableB)

SELECT a.*, b.*
FROM TableA a
[LEFT or INNER] JOIN TableB b ON (b.a_id = a.id)
a1ex07
I need all records from Table A and all records from Table B. There is no id to join them on, no columns are related.
teamdane
In this case I'd have 2 independent queries.
a1ex07
A: 

If there's no way to relate the two tables to each other, then you can't use a JOIN to grab records from both. You COULD use a UNION query, but that presumes that you can match up fields from each table, as a UNION requires you to select the same number/type of fields from each table.

SELECT 'pageinfo' AS sourcetable, page.id, page.images, page.this, page.that
WHERE page.id = $id

UNION

SELECT 'product' AS sourcetable, products.id, products.image, product.other, product.stuff

But this is highly ugly. You're still forcing the DB server to do two queries in the background plus the extra work of combining them into a single result set, and then you have to do extra work to dis-entangle in your code to boot.

It's MUCH easier, conceptually and maintenance-wise, to do two seperate queries instead.

Marc B