简体   繁体   English

如何组合这些多个 MySQL 查询?

[英]How Can I Combine These Multiple MySQL Queries?

I have a couple of tables where I need to perform some queries.我有几个表需要执行一些查询。 The code looks like this:代码如下所示:

$query = "SELECT * FROM table1,table2 WHERE table1.item1='$item1' AND table2.item2='1' AND table1.item2=table2.item2";

The problem I a have is I have about 25 similar queries to make, the only difference is我遇到的问题是我有大约 25 个类似的查询要进行,唯一的区别是

table2.item2='1'
table2.item2='2'
...
table2.item2='25'

What I'd like to be able to do is to write just one query, but still be able to extract the data.我希望能够做的是只编写一个查询,但仍然能够提取数据。 I think some sort of loop function (I'm using PHP) should be able to do it, but I haven't been able to come up with one.我认为某种循环函数(我正在使用 PHP)应该能够做到这一点,但我一直无法想出一个。

Main problem is the numbers 1-25 in my example are not consecutive numbers - they actually look like 204, 208, 465, 646, etc.主要问题是我的例子中的数字 1-25 不是连续的数字——它们实际上看起来像 204、208、465、646 等。

Any help greatly appreciated!非常感谢任何帮助!

use join使用join

SELECT * FROM table1 t1 join table2 t2
on t1.item2=t2.item2
WHERE t1.item1='$item1' AND 
t2.item2 BETWEEN 1 AND 25

Use JOIN to fetch data from multiple tables.使用JOIN从多个表中获取数据。

Try this尝试这个

$sql = "";
$sql .= "SELECT * FROM table1 t1 join table2 t2
on t1.item2=t2.item2
WHERE t1.item1='$item1'"; 

for($i = 1; $i<=25; $i++)
    $sql .= " AND t2.item2='$i' ";

Edit: As per you comment, following is the option you can use.编辑:根据您的评论,以下是您可以使用的选项。 For simplicity, just take all the values in an array and use foreach to loop through it and form your query.为简单起见,只需获取数组中的所有值并使用 foreach 循环遍历它并形成您的查询。

$array = array("204", "208", "465", "646");

foreach($array as $arr)
    $sql .= " AND t2.item2='$arr' ";

看看MYSQL JOINS它用于从多个表中获取数据。

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

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