MySQL
table1:
+--------+------+
| listid | type |
+--------+------+
| 1 | a |
+--------+------+
| 2 | a |
+--------+------+
| 3 | b |
+--------+------+
table2:
+----+--------+------+
| id | listid | code |
+----+--------+------+
| 1 | 1 | ax |
+----+--------+------+
| 2 | 1 | bx |
+----+--------+------+
| 3 | 2 | ax |
+----+--------+------+
| 4 | 2 | bx |
+----+--------+------+
| 5 | 2 | cx |
+----+--------+------+
| 6 | 3 | ax |
+----+--------+------+
| 7 | 3 | bx |
+----+--------+------+
Task
In one query, I want to check if:
1) in the table table2 only "ax" & "bx" are listed as code
2) the type of the listid I get in 1) is "a" in the table 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';
}
Output
listid = 1
listid = 2 is false, because "cx" is also included in table2
listid = 3 is false, because it has type "b" in table1
I hope this makes sense :)
SELECT t1.listid
FROM t1
WHERE type = 'a'
AND id NOT IN
(
SELECT listid
FROM t2
WHERE code NOT IN ('ax', 'bx')
)
This will also match records from t1
which have no corresponding records in t2
at all.