mysql,连接2个表,并检查2个条件

时间:2011-01-21 22:55:25

标签: php sql mysql join

的MySQL

表1:

+--------+------+
| listid | type |
+--------+------+
|    1   |  a   |
+--------+------+
|    2   |  a   |
+--------+------+
|    3   |  b   |
+--------+------+

表2:

+----+--------+------+
| id | listid | code |
+----+--------+------+
|  1 |    1   |  ax  |
+----+--------+------+
|  2 |    1   |  bx  |
+----+--------+------+
|  3 |    2   |  ax  |
+----+--------+------+
|  4 |    2   |  bx  |
+----+--------+------+
|  5 |    2   |  cx  |
+----+--------+------+
|  6 |    3   |  ax  |
+----+--------+------+
|  7 |    3   |  bx  |
+----+--------+------+

任务

在一个查询中,我想检查是否:

1)表 table2 仅“ax”& “bx”列为代码

2)我在1)中输入的 listid 的类型是表格中的“a” table1

PHP

$a = mysql_query("SELECT t1.listid FROM table1 AS t1, table2 AS t2......");
$b = mysql_fetch_assoc($a);

if($b['listid'])
{
    echo $b['listid'];
}
else
{
    echo 'nothing found';
}

输出

listid = 1

listid = 2是假的,因为“cx”也包含在 table2

listid = 3是假的,因为它在 table1 中有“b”类型

我希望这是有道理的:)

1 个答案:

答案 0 :(得分:1)

SELECT  t1.listid
FROM    t1
WHERE   type = 'a'
        AND id NOT IN
        (
        SELECT  listid
        FROM    t2
        WHERE   code NOT IN ('ax', 'bx')
        )

这也会匹配来自t1的{​​{1}}中没有相应记录的记录。