简体   繁体   English

使用PHP进行SQL查询-从以逗号分隔并链接的一列中获取数据

[英]SQL query with PHP - Fetch data from one column separated by comma and linked

I have problem with sql query, 我对sql查询有疑问,

I have two tables 我有两张桌子

** T1 **
ID | Cat
---------
1  | TEXT

2  | TTTT

... ...

** T2 **

**ID | TEXT | AutID | T1ID  | TEXT2 | TEXT ...**

1    | text | $ID   | 1,2   | text  | text

2    | text | $ID   | 3,4,6 | text  | text

and I need sql query to fetch data from table 2 (t2) from column t1.ID but all data in row1 = 1,2 and in row2 = 3,4,6 and how I can make link from that. 我需要SQL查询从列t1.ID从表2(t2)中获取数据,但row1 = 1,2和row2 = 3,4,6中的所有数据,以及如何从中进行链接。

What I have for now is 我现在所拥有的是

$query = "SELECT * 
FROM T2, T1
WHERE AutID=$ID 
AND T1.Id=T2.T1ID";

and for link I have use while loop 对于链接我有使用while循环

$catName = $row["Cat"];
$catID = $row["Id"];

echo "<a href=file.php?ID=".$catID . ">" .$catName."</a>

To improve on bumperbox's answer and reduce the queries to the server. 为了改善bumperbox的答案并减少对服务器的查询。 Rather than doing multiple queries, you could use an IN statement: 您可以使用IN语句,而不是执行多个查询:

$query2 = "SELECT * FROM T1 WHERE ID in (" . explode(',', $row['T1ID']) . ")";
$res2 = mysql_query($query2) || die(mysql_error());

because you are storing multiple keys in the T1ID column you need to query the data, then split it into separate keys in php, then perform a 2nd query to get the data you want 因为您要在T1ID列中存储多个键,所以需要查询数据,然后将其拆分为php中的单独键,然后执行第二次查询以获取所需的数据

there are better ways to design a database, if that is a possibility then i would look at a redesign, but if you are stuck with this structure, then you can do the following 有更好的方法来设计数据库,如果有可能,那么我会考虑重新设计,但是如果您坚持使用这种结构,则可以执行以下操作

$query = "SELECT * FROM T2 WHERE AutID=$ID";

$res = mysql_query($query) || die(mysql_error());

while ($row = mysql_fetch_assoc($res)) {

   $keys = explode(',', $row['T1ID']);

   foreach ($keys as $key) {
      $query2 = "SELECT * FROM T1 WHERE ID=$key";

      $res2 = mysql_query($query2) || die(mysql_error());

      // do what you want with your data now
   }
}

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

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