根据另一个表的列值从表中选择记录

时间:2013-08-28 20:40:49

标签: php mysql sql

我知道形成这个查询是微不足道的,但我无法构建确切的查询。根据我到目前为止所读到的内容,解决方案可能包括加入两个表。这是问题所在:

TABLE_ONE {S_NO, DK_NO, FRM , DATE}

TABLE_TWO {S_NO, DK_NO , TO}

我想根据TABLE_ONE的输入值和DK_NO的TO字段或TABLE_TWO的FRM字段检查的值,从TABLE_ONE中选择一条记录

到目前为止,试验不成功:

1)

$sql = "select * from TABLE_ONE where DK_NO like '%".$dkno."%' and (FRM='".$department."' or  (TABLE_TWO.DK_NO like '%".$dakno."%' and TABLE_TWO.TO='".$department."'))";

2)

$sql = "select * from TABLE_ONE where DK_NO like '%".$dkno."%' and (FRM='".$department."' or   TABLE_TWO.TO='".$department."')";

2 个答案:

答案 0 :(得分:1)

推荐阅读:JOIN

使用内部联接:

"select t1.* 
from table_one t1 inner join table_two t2 on t1.dk_no = t2.dk_no
where (t1.frm = '". $department. "' or t2.to = '".$department. "') 
    and t1.dk_no like '%" . $dkno . "%'";

答案 1 :(得分:1)

您需要加入表格。尝试像 -

这样的东西
SELECT
    T1.*
FROM
    TABLE_ONE T1
JOIN
    TABLE_TWO T2
ON
    T1.DK_NO = T2.DK_NO
WHERE
    T1.DK_NO like '%".$dkno."%' 
AND
    (T1.FRM='".$department."' OR TABLE_TWO.TO='".$department."')