复杂的选择语句

时间:2013-08-06 13:38:38

标签: php sql

我有4张桌子

Tbl_Items: 
   Asset Id, 
   Asset_name, 
   Workshop,
   PAT_PASS

(研讨会和PAT_PASS是YES或NO.Workshop = YES和PAT_PASS = NO表示此项目不可用于租用..)

Tbl_Project_details:
   Project_id, 
   Project_start_date, 
   project_end_date

TBL_Project_items:
   Project_id, 
   Asset_id,
   Start_date,
   End_date

我需要做一个select语句,允许我显示tbl_Items中的所有项目除外:

1) Those that are already in use on another project on the dates that I need them.
2) Are in the workshop. (Workshop = YES)
3) Are not PAT Tested (PAT_PASS = NO)

到目前为止,我已经开始使用这样一个简单的声明:

$post_project_id = "13-1309.01";  //this is just an example number..

$sql = 
"SELECT * FROM Project_details 
Where Project_id = '$post_project_id' ";  
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) 
{
$hire_start_date = $row['Start_date']; // we find out our projects start date
$hire_end_date = $row['End_date'];     // we find out our projects end date
}  

$result=mysql_query("SELECT Items.Asset_id, Items.Name  
FROM 
Items,Project_items 
WHERE
Project_details.Start_date < '$hire_start_date' 
AND 
Project_details.End_date > '$hire_end_date'") 
or die(mysql_error());

while($row = mysql_fetch_array($result))
{
// fill up an option box with the results
}

即使这个基本脚本似乎也不起作用!这是我第一次尝试从多个表中进行选择,所以这是一个陡峭的学习曲线!

谢谢!

3 个答案:

答案 0 :(得分:0)

$StartDate$EndDate是您的约会日期:

 SELECT ITEM.asset_id,
        ITEM.asset_name,
        ITEM.workshop,
        ITEM.pat_pass
   FROM Tbl_Items ITEM
        LEFT JOIN Tbl_Project_Items PJITEM
           ON PJITEM.asset_id = ITEM.asset_id
           AND PJITEM.start_date BETWEEN $StartDate AND $EndDate
           OR PJITEM.end_date BETWEEN $StartDate AND $EndDate
   WHERE ITEM.workshop = 'no'
     AND ITEM.pat_pass = 'yes' 
     AND PJITEM.asset_id IS NULL

谁是帕特?

答案 1 :(得分:0)

我会选择子查询:

SELECT * FROM Tbl_Items AS i WHERE

这应符合您的(1.)条件:“只接受那些选择没有任何出现的记录”:

0 = (
SELECT COUNT(1) FROM TBL_Project_items AS pi
WHERE i.Asset_Id = pi.Asset_Id
AND Start_date < $hire_start_date
AND End_date > $hire_end_date
)

研讨会条件(2.):

AND WORKSHOP != "YES"

拍摄测试条件(3):

AND PAT_PASS != "NO"

答案 2 :(得分:-1)

一个问题:

WHERE
Project_details.Start_date < '$hire_start_date' 
AND 
Project_details.End_date > '$hire_end_date'") 

“Start_date”和“End_date”列不在“Project_details”表中。在该表中,这些列似乎被命名为“Project_start_date”和“Project_end_date”。