开发者

PHP MySql query 2 tables that have no common attributes at the same time?

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


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜