开发者

Can anyone help me with this query?

开发者 https://www.devze.com 2023-02-19 10:21 出处:网络
I have id\'s stored in a row of my database, and the ids are seperated by commas ex: 12,3,5,2,7 and i am trying to create a query by imploding the string and selecting each one of the id\'s, from an

I have id's stored in a row of my database, and the ids are seperated by commas ex:

12,3,5,2,7

and i am trying to create a query by imploding the string and selecting each one of the id's, from another table, but i am trying to avoid looping the query because of performance issues. is there anyway around a loop? I am currently using mysqli prepared statements.

$stmt = $DBH->prepare("SELECT ids FROM list WHERE user = ?");
    $stmt->bind_param("s",$userid);
    $stmt->execute();
    $stmt->bind_result($ids);
        $stmt->fetch();

stored in ids is just a list of numbers, now how can i query another table looking for the rows that match each one of the numbers in the list, similar to a tagging system. The numbers or the amount of numbers are not predetermined or known before making the query.

EXAMPLE:

Table 1: Where the actual Information is stored

ID    Information
开发者_如何学C
1     /*information stored for id number 1*/
2     /*information stored for id number 2*/
3     /*information stored for id number 3*/
4     /*information stored for id number 4*/
5     /*information stored for id number 5*/



Table 2: The users name and a list of id's stored (The ID_LIST will be constantly changing and expanding, the numbers contained will not be predefined.)

USER      ID_LIST

exampleuser    1,3,5
exampleuser2   1,4,12,22

The first query will be obtaining the list of ids from Table 2 and separating them. Then i need to get the information from each id in table 1 from the ids in the id list in table 2. but i am trying to avoid a loop, hopefully this is specific enough, if not please let me know.


The rest of your code would be something like

// This doesn't need to be a prepared statement
if ($result = $DBH->query("SELECT * FROM ids_table WHERE id IN ({$ids})")) {
    while ($row = $result->fetch_assoc()) {
        // Do whatever you want
    }
}


Quote:-- "I have id's stored in a row of my database, and the ids are seperated by commas ex:"

This is basically a bad design!

You should store the ids in a single column in another table with a key of whatever the key for you table is now , plus the id.


SELECT * FROM tbl WHERE FIND_IN_SET(id, '12,3,5,2,7')

So you can specify any field that contains a list of numbers separated by comma as a second parameter of FIND_IN_SET

0

精彩评论

暂无评论...
验证码 换一张
取 消