简体   繁体   English

PHP SQL查询2表

[英]PHP SQL Query 2 Tables

I need to query the database with a php query. 我需要使用php查询来查询数据库。

I need to get the id that matches $somevalue and the with that ID query table 2 so I can get a field value contained in that row where the id is found. 我需要获取与$ somevalue匹配的ID以及与该ID查询表2匹配的ID,以便获取包含该ID的那一行中包含的字段值。

$somevalue = '123';


Select id from table1 where $somevalue = id

...so we have the ID ... now we query table 2

select id, field2 from table2 where id = $id

echo $id;
echo $field2

How can I do this in a php query? 如何在php查询中执行此操作?

Simply try this. 只需尝试一下。

 select t2.id, t2.field2 from table2 t2, table1 t1 where t1.id = t2.id and t1.id = $someValue

Full Code is as below 完整代码如下

$query = sprintf("select t2.id, t2.field2 from table2 t2, table1 t1 where t1.id = t2.id and t1.id = '%s'",
    mysql_real_escape_string($somevalue));

// Perform Query
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
    echo $row['id'];
    echo $row['field2'];
}

Your query syntax should look like: 您的查询语法应类似于:

Select id from table1 where id = $somevalue

But why you want the same id, with which you are searching? 但是,为什么要使用相同的ID进行搜索? You could directly do this: 您可以直接这样做:

select id, field2 from table2 where id = $somevalue

Looks like complete mess :( 看起来像是一团糟:(

Anyway, you can Check This link on how to execute queries in PHP 无论如何,您可以选中此链接以了解如何在PHP中执行查询

尝试这个:

"SELECT * FROM table1 as t1 Left JOIN table2 as t2 ON t1.id = t2.id WHERE t1.id = ".$somevalue.""

Use inner join 使用内部联接

SELECT table2.id table2.field FROM table1
INNER JOIN table2 ON table2.id = table1.id 

haven't test the code, and i am fairy new to SQL (joins). 还没有测试代码,我是SQL的新手(加入)。 But you see the patern :) 但是你看到的模式:)

You should be able to achieve this using a JOIN , here is an example using the the code from the question 您应该可以使用JOIN来实现这一点,这是使用问题代码的示例

SELECT t2.field2
FROM table1 t1
JOIN table2 t2
   ON t1.id = t2.id
WHERE t1.id = $someValue

What doesn't look right here is joining the tables on their Id columns. 在这里看起来不正确的是将表连接到其Id列。 This is typically the primary key and unlikely to be used in both sides of a join. 这通常是主键,不太可能在连接的两侧使用。

A join is made from one table to another to reconstruct the data model. 从一个表到另一个表进行联接以重建数据模型。 To make this a little more concrete I will change table1 to People and table2 to Addresses . 为了更具体一点,我将table1更改为People并将table2更改为Addresses The following query gets the StreetName for a particular person via the People table. 以下查询通过People表获取特定人的StreetName In this case the People table has a column AddressId which holds the Id for this person in the Addresses table 在这种情况下, People表中有一栏AddressId持有的Id为这个人的地址表

SELECT a.StreetName
FROM People p
JOIN Addresses a
   ON p.AddressId = a.id
WHERE t1.id = $someValue

You can then apply whatever mechanism PHP offers to run the query 然后,您可以应用PHP提供的任何机制来运行查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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