简体   繁体   English

使用PDO根据mySQL中其他两个表的结果从表中选择行

[英]Select rows from a table based on results from two other tables in mySQL using PDO

I have structured my Database in 3 tables: 我将数据库分为3个表:

members       -       membersitems       -     items
---------------------------------------------------------
memberid      -       memberitemid       -     itemid
username      -       itemid             -     itemname
password      -       memberid           -     itemtype
etc

The idea is that every time a member gets a new item a row is added to membersitems . 这个想法是,每次成员获得新项目时,都会在membersitems添加一行。 The membersitems table is intended to join the two tables. membersitems表旨在将两个表连接membersitems I'm not sure if there is a simpler way using only two table and JOIN ?. 我不确定是否只有两个表和JOIN吗?

Using the $_SESSION["memberid"] I am selecting rows in the membersitems table where the memberid is the same as the session: 使用$_SESSION["memberid"]我选择的行membersitems表,其中MEMBERID相同的会话:

$stmt = $db->prepare('SELECT itemid FROM membersitems WHERE memberid = :memberid');
$stmt->execute(array(':memberid' => $_SESSION['memberID']));
$array = $stmt -> fetchAll(PDO::FETCH_ASSOC);
    foreach($array as $row) {
    $itemid[] = $row['itemid'];
}

I'm not sure the best way to collate this data for the next step, but I tried using a comma separated string: 我不确定下一步如何整理此数据的最佳方法,但是我尝试使用逗号分隔的字符串:

$itemids = '[' .implode(',', $itemid). ']';
/// echos out: [1,2,3,4,5,6,6,6,]

Note there are three of item 6. I would like to display item 6, three times. 请注意,项目6中有3个。我想显示3次项目6。

I am then trying to select the data in the items table using the following code, which isn't working, but isn't returning an error: 然后,我尝试使用以下代码在项目表中选择数据,该代码不起作用,但未返回错误:

    $arr = $itemids;     
    $in  = str_repeat('?,', count($arr) - 1) . '?';
    $sql = "SELECT * FROM items WHERE itemid IN ($in)";
    $stm = $db->prepare($sql);
    $stm->execute($arr);
    $data = $stm->fetchAll();

I would also like some advice on separating the returned data and perhaps sorting by type. 我还希望获得一些有关分离返回的数据以及可能按类型排序的建议。

I am quite new to server-side scripting and mySQL, but can handle criticism. 我对服务器端脚本和mySQL还是很陌生,但是可以处理批评。 Please be as critical as possible but assume my knowledge is basic. 请尽可能严格,但要假设我的知识是基础。 The accepted answer will be the one that is teaching rather than just a solution. 可接受的答案将是正在教授的答案,而不仅仅是解决方案。

I know there are similar questions, I have tried other examples that are a similar concept to this but struggled to fill in the gaps where there were nuances. 我知道也有类似的问题,我尝试了其他示例,这些示例与此概念相似,但是努力填补存在细微差别的空白。

Thank you in advance. 先感谢您。

This I think is the query you are looking for. 我认为这是您要查找的查询。 I was not totally sure what result you wanted but this should give you a push in the right direction. 我不确定您想要什么结果,但这应该可以向正确的方向发展。

$q = "SELECT i.* 
      FROM items i
          JOIN membersitems m ON m.itemid = i.itemid
      WHERE i.memberid = :memberid";



$stmt = $db->prepare($q);
$stmt->execute(array(':memberid' => $_SESSION['memberID']));

As hinted in some of the comments, this is a very straightforward SQL concept called JOIN. 正如一些评论所暗示的,这是一个非常简单的SQL概念,称为JOIN。

You are using WHERE IN which has a close cousin in the JOIN family called INNER JOIN. 您正在使用WHERE IN,它在JOIN家族的近亲中叫做INNER JOIN。

You'll need to read some documentation on JOIN, but suffice it to say that INNER JOIN can be used to filter one table using another table. 您需要阅读一些有关JOIN的文档,但足以说明INNER JOIN可用于过滤另一个表中的一个表。 For example, if you want to get items out of your items table filtered by membersid from your join table, you could do so with a query like this: 例如,如果您要从连接表中的membersid过滤的项目表中获取项目,则可以使用如下查询:

SELECT i.* 
FROM items i
INNER JOIN membersitems m
ON i.itemid = m.memberid
WHERE m.memberid = :memberid

In most cases, this will be a much more efficient way to get the items associated with a given memberid than executing two queries (and as mentioned in the comments it's best to avoid comma-serializing ids in PHP and then requerying). 在大多数情况下,与执行两次查询相比,这是一种获取与给定memberid关联的项目的更有效的方法(如注释中所述,最好避免在PHP中对逗号进行序列化的ID,然后再进行查询)。

As a side note, a subquery would be another way to achieve your goal, using similar syntax to your current query: 附带说明一下,子查询将是使用与当前查询类似的语法来实现您的目标的另一种方式:

SELECT * 
FROM items 
WHERE itemid 
IN (
  SELECT itemid 
  FROM membersitems 
  WHERE memberid = :memberid
)

One more note. 还有一张便条。 Your table schema may be redundant depending on what kind of relationship you have between members and items. 您的表架构可能是多余的,具体取决于您在成员和项目之间的关系类型。 You'll want to do some reading on schema design for One-To-Many vs Many-To-Many. 您需要对一对多与多对多的模式设计进行一些阅读。 The design you have is a good one if it is possible for: 1) One member to have many items AND 2) One item to have many members However, if every item in the items table is associated with one and only one member (which I suspect might be the case), you could use a schema like this one: 如果可能的话,您拥有的设计就是一个好的设计:1)一个成员拥有多个项目并且2)一个项目拥有多个成员但是,如果项目表中的每个项目都与一个成员相关联并且只有一个成员(我怀疑可能是这种情况),您可以使用这样的模式:

members       -     items
------------------------------
memberid      -     itemid
username      -     memberid
password      -     itemname
etc

In the above schema, each item is responsible for knowing its parent member, and that is sufficient to execute both of the above queries (simply substituting the appropriate table names). 在上面的模式中,每个项目都负责了解其父成员,这足以执行上述两个查询(只需替换适当的表名)。

A final note. 最后的笔记。 This is by no means a requirement, but it is pretty common for tables to simply have id columns called id (not itemsid, membersid). 这绝不是必需的,但是对于表来说,仅具有称为id id列(不是itemsid,membersid)是很常见的。 It's pretty common sql convention to separate words with underscores for join tables (eg items_id and members_id ). 在连接表中用下划线分隔单词(例如items_idmembers_id )是非常常见的sql约定。

Have fun and good luck! 玩得开心,祝你好运!

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

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