简体   繁体   English

从sql数据库获取数据,然后通过php将其用于选择查询

[英]Getting data from sql database and then use it for select query via php

I have this allocation table: 我有这个分配表:

PROJECT_ID | NAME_ID
1                1
1                2
2                1
2                2

My php Code looks as following: 我的php代码如下所示:

<html>
<body>
<?php
mysql_connect("xxx","xxx","xxx") 
    or die ("Connection failed");
mysql_select_db("xxx") 
    or die ("Connection failed");
$res = mysql_query("SELECT PROJECT_ID FROM Projects_Names WHERE NAME_ID=1 AND 2");
$num = mysql_num_rows($res);
echo "$num Projects found<br />";

while($dsatz = mysql_fetch_assoc($res))
{
echo $dsatz["PROJECT_ID"] . "<br />";
}

?>

This will then give me the following output: 然后,这将给我以下输出:

2 Projects found
1
2

So far so good. 到现在为止还挺好。 But what I basically want is to find out the names of the projects where employee 1 and employee 2 are both involved in. I have two more tables. 但是我基本上想要的是找出雇员1和雇员2都参与的项目的名称。我还有两个表。 A Projects table with the project Name, ID etc... and a Employee table with Name, ID etc... 具有项目名称,ID等的Projects表和具有名称,ID等的Employee表...

I basically now want to say: 我现在基本上想说:

"look in the Projects table for the IDs that were just given as output (1,2) and give me the names of these projects" “在“项目”表中查找刚刚作为输出提供的ID(1,2),并给我这些项目的名称”

I hope someone will give me some input on how to solve this, I just started sql + php yesterday, so theres much to learn :) 我希望有人能给我一些有关如何解决此问题的意见,我昨天才刚开始使用sql + php,所以有很多东西要学习:)

Your best bet is to use a combination of GROUP BY with COUNT and HAVING to get what you want 最好的选择是结合使用GROUP BYCOUNTHAVING来获得想要的东西

SELECT project_id, COUNT(DISTINCT name_id) AS `name_count`
FROM projects_names
WHERE name_id IN (?,?,...)
GROUP BY project_id
HAVING `name_count` = n

Here you would list all name_id values you were interested in and n would equal the number of name_id values search for. 在这里,您将列出所有感兴趣的name_id值,并且n等于要搜索的name_id值的数量。 So if you are looking for name_id 1 and 2, you would use n = 2. This means find all projects where those to id are working, but there could be additional name_id's involved as well (those wouldn't be included in the count as they were filtered out). 因此,如果您要查找name_id 1和2,则将使用n =2。这意味着找到所有要运行id的项目,但是可能还会涉及到其他name_id(不包括在计数中)他们被过滤掉了)。

That's wrong syntax. 那是错误的语法。 You should either write it separately like this: 您应该这样单独编写:

$res = mysqli_query($con, "SELECT PROJECT_ID FROM Projects_Names WHERE NAME_ID=1 AND NAME_ID = 2");

or use in 或使用in

$res = mysqli_query($con, "SELECT PROJECT_ID FROM Projects_Names WHERE NAME_ID in (1,2)");

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

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