简体   繁体   English

如何为两个相关表创建MYSQL记录源

[英]How to create MYSQL record source for two related tables

I currently have a page that displays player information from one table named "tblplayers". 我目前有一个页面显示名为“ tblplayers”的表中的玩家信息。 The query I am currently using is: 我当前使用的查询是:

$result = mysql_query("SELECT * FROM tblPlayers WHERE lng_RecordID_PK = '".$playerid."' ");

I have a second table named "tblMatches" containing match results for the players. 我还有一个名为“ tblMatches”的表格,其中包含玩家的比赛结果。 I want the recordset to include the rows from "tblMatches" WHERE "P1_ID" OR "P2_ID" is equal to the "lng_RecordID_PK" field from "tblPlayers". 我希望记录集包括“ tblMatches”中的行,“ P1_ID”或“ P2_ID”等于“ tblPlayers”中的“ lng_RecordID_PK”字段。

How can I revise my $result query so that it returns: 如何修改$ result查询,使其返回:

  • one row from tblPlayers 来自tblPlayers的一行
  • multiple rows from tblMatches 来自tblMatches的多行

??? ???

Thanks for helping me out. 谢谢你的协助。

That's called a 'join': 这就是所谓的“加入”:

SELECT tblPlayers.*, tblMatches.*
FROM tblPlayers
LEFT JOIN tblMatches ON Ing_RecordID_PK IN (P1_ID, P2_ID)

You are asking about joining two tables where the second table potentially has multiple records for each one in the first table. 您正在询问如何联接两个表,其中第二个表可能在第一个表中每个表都有多个记录。 This is a one-to-many or 1:N join, and most often done using a LEFT JOIN meaning you want everything in the "left" table, and all the records that match from the "right" table, and that you may have some records on the "left" side with no matches. 这是一对多或1:N的LEFT JOIN ,并且通常使用LEFT JOIN来完成,这意味着您希望“左”表中的所有内容以及“右”表中匹配的所有记录,并且您可能在“左侧”有一些记录,没有匹配项。

Your query would look like this: 您的查询如下所示:

SELECT *
FROM tblPlayers
LEFT JOIN tblMatches
    ON (tblPlayers.lng_RecordID_PK = tblMatches.P1_ID
        OR tblPlayers.lng_RecordID_PK = tblMatches.P2_ID)
WHERE tblPlayers.lng_RecordID_PK = @PlayerID;

Bits of advice: 一点建议:

  • Avoid selecting all columns (*) and instead select just those that you need for the query. 避免选择所有列(*),而只选择查询所需的列。
  • Consider using parameterized queries to avoid SQL injection attacks. 考虑使用参数化查询来避免SQL注入攻击。 If your variable were to be submitted or altered maliciously, it could result in compromised data or security. 如果要恶意提交或更改您的变量,则可能导致数据或安全性受损。 (See PHP Data Objects for example.) (例如,请参阅PHP数据对象 。)

There is no way to get rows from two different tables in the way you are describing. 无法以您描述的方式从两个不同的表中获取行。 You could not get a row from one table, and two rows from another one. 您无法从一个表中获得一行,而从另一张表中获得两行。 What you could is do two separate queries, or use a JOIN statement to join the two tables together, and then receive results from the resulting joined table. 您可以执行两个单独的查询,或者使用JOIN语句将两个表连接在一起,然后从生成的连接表中接收结果。 If you provide more information about your table structure I am sure more help can be given. 如果您提供有关表结构的更多信息,我相信可以提供更多帮助。

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

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