简体   繁体   中英

get info from 2 tables at once?

I need to get info from 2 tables in one query, I searched for it on google and it came up with joins? I got this code

mysql_query("SELECT code, url FROM apilinks, links WHERE apilinks.code='$code' and links.code='$code'");

but it doesn't seem to work, it outpus this mysql error

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/codyl/public_html/projects/tests/tirl/code.php on line 18

I need to have it find url and code, in both the links table and the apilinks table, because the url has a get variable, and 'apilinks' is setup differently than 'links' so it will have the same looking url but it has to check both tables

I don't think your error is from your SQL query, but anyway:

Your SQL query generates a cartesian product. Every row in apilinks is joined with every row in links. This is rarely what you want. You need to add a JOIN condition to the WHERE clause.

From your query, I guess code is the column you want to join on.

SELECT links.code, url 
FROM apilinks, links 
WHERE apilinks.code=links.code
AND links.code='$code'

Or with using an explicit join, which may be more obvious to you:

SELECT links.code, url 
FROM apilinks INNER JOIN links ON apilinks.code=links.code
WHERE links.code='$code'

I think you need to specify which code column you want:

SELECT links.code, links.url 
FROM   apilinks, links 
WHERE  apilinks.code='$code' 
AND    links.code='$code'

Another syntax:

mysql_query("SELECT a.code, l.url FROM apilinks a, links l WHERE a.code='$code' and l.code='$code'");

Note that I am assuming the url field is in the links table.

SELECT a.code, a.url 
FROM apilinks a, links l 
ON ( a.code = l.code )
WHERE a.code = "$code";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM