简体   繁体   中英

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

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.

Main problem is the numbers 1-25 in my example are not consecutive numbers - they actually look like 204, 208, 465, 646, etc.

Any help greatly appreciated!

use 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.

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.

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

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

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

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