【问题标题】:mysql, joining 2 tables, and checking for 2 conditionsmysql,加入2个表,并检查2个条件
【发布时间】:2011-01-21 22:55:24
【问题描述】:

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" 被列为 code

2) 我在 1) 中得到的 listid 的类型是表 table1

中的“a”

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 为假,因为 table2

中也包含“cx”

listid = 3 为假,因为它在 table1

中有类型“b”

我希望这是有道理的:)

【问题讨论】:

    标签: php sql mysql join


    【解决方案1】:
    SELECT  t1.listid
    FROM    t1
    WHERE   type = 'a'
            AND id NOT IN
            (
            SELECT  listid
            FROM    t2
            WHERE   code NOT IN ('ax', 'bx')
            )
    

    这也将匹配来自t1 的记录,这些记录在t2 中根本没有对应的记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-05
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多