查找table1中的所有行,其中table2中的零行通过外键链接到它

时间:2015-09-26 08:54:47

标签: mysql

外键trade.ticker_id指向ticker.id。

我想查找' ticker'中的所有行在交易中有零行的'与之相关联。

mysql> describe trade; 
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| time      | datetime    | NO   |     | NULL    |                |
| price     | float       | NO   |     | NULL    |                |
| quantity  | int(11)     | NO   |     | NULL    |                |
| source    | varchar(64) | YES  |     | NULL    |                |
| buyer     | varchar(64) | YES  |     | NULL    |                |
| seller    | varchar(64) | YES  |     | NULL    |                |
| initiator | varchar(64) | YES  |     | NULL    |                |
| ticker_id | int(11)     | YES  | MUL | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
9 rows in set (0,00 sec)

mysql> describe ticker;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(64)  | NO   |     | NULL    |                |
| long_name   | varchar(250) | YES  |     | NULL    |                |
| exchange_id | int(11)      | YES  | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
4 rows in set (0,00 sec)

2 个答案:

答案 0 :(得分:0)

您可以使用left joinis null或换句话说反加入

select tc.* from ticker tc
left join trade tr on tr.ticker_id = tc.id
where tr.ticker_id is null

答案 1 :(得分:0)

试试这个:

SELECT * FROM ticker WHERE id NOT IN (SELECT ticker_id FROM trade)