php 选择多个表mysql
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19649445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
select multiple tables mysql
提问by user2926655
I am trying to select two tables with where clause,
我正在尝试使用 where 子句选择两个表,
The problem: I am getting more than 2 result. something like 123451111
I only have two ids with the value 1. I think I am doing it wrong.
问题:我得到的结果超过 2 个。就像123451111
我只有两个值为 1 的 id。我想我做错了。
The tables don't have the same structure and are not related by any means. Any ideas?
这些表没有相同的结构,并且没有任何关联。有任何想法吗?
<?php include_once("config.php");
$s = '1';
$stmt =$mydb->prepare("select * FROM table1,table2 where table1.id = ? or table2.id = ?");
stmt->bind_param('ss', $s, $s);
echo $mydb->error;
$stmt->execute();
?>
<?php
$results = $stmt->get_result();
while ($row = $results->fetch_assoc()) {
echo $row['id']."<br/>";
}
?>
回答by Aditya Kakirde
You need to have a join between table1 and table2 on some unique column, say id.
您需要在某个唯一列(例如 id)上在 table1 和 table2 之间建立连接。
select * FROM table1,table2 where table1.id = table2.id;
Additionally you can have multiple filter conditions( say you want to filter the tables on id=101 -
此外,您可以有多个过滤条件(假设您想过滤 id=101 上的表 -
select *
FROM table1,table2
where table1.id = table2.id
and table1.id = 101;
Hope this helps. Whenever you have multiple tables in a SQL statement, you need to join them otherwise the engine would make cartesian product as it happens in Cartesian product of mathematical set theory.
希望这可以帮助。每当您在 SQL 语句中有多个表时,您都需要加入它们,否则引擎会产生笛卡尔积,就像数学集合论的笛卡尔积一样。
Basically you should have at least n-1 join conditions where n is the number of tables used.
基本上你应该至少有 n-1 个连接条件,其中 n 是使用的表的数量。
回答by Filipe Silva
Your question is a little problematic, but if your problem is not getting two id's, but you are getting one correctly with the use of a JOIN, you may be looking for a IN clause:
您的问题有点问题,但是如果您的问题不是获得两个 id,而是使用 JOIN 正确获得一个,那么您可能正在寻找 IN 子句:
SELECT *
FROM table1,table2
WHERE table1.id = table2.id
AND table1.id IN (ID1, ID2);
Using IN instead of = lets you match multiple values to the table.id. This way, you get data from both tables and you get both ID's
使用 IN 而不是 = 可以将多个值匹配到 table.id。这样,您可以从两个表中获取数据并获得两个 ID
回答by Oki Erie Rinaldi
This is join usage :
这是连接用法:
select t1.*,t2.* FROM table1 t1
left join table2 t2
on t1.id = t2.id
where t1.id = "keyword"