如何选择表中的所有行,并与另一个表进行交叉检查?

时间:2011-11-21 00:56:26

标签: mysql sql

MySQL表

MySQL:植物

+----+--------+
| id | plant  |
+----+--------+
| 1  | tree   |
+----+--------+
| 2  | flower |
+----+--------+
| 3  | tree   |
+----+--------+

MySQL:树

+----+------+
| id | type |
+----+------+
| 1  | hard |
+----+------+
| 3  | soft |
+----+------+

我正在尝试做什么

我想选择表格植物中的所有行。

但如果plant = tree,那么表格中的类型必须为hard才能显示。

因此,上面的示例应输出:1=tree2=flower

3=tree应排除在外,因为type = soft

到目前为止我尝试了什么......但是没有用到

a)我想我不能使用union,因为列不同。

b)我已经尝试了left join,但这也不起作用:

select p.id, p.plant
from plants AS p
left join
(
   select `id`, `type`
   from `trees`
) AS t ON p.id = t.id
WHERE t.type = 'hard'

关于我如何做到的任何想法?

3 个答案:

答案 0 :(得分:1)

select p.id, p.plant from plants as p left join trees as t on (p.id = t.id) where t.type = 'hard' or t.type is null

我希望这有效。无论如何,当前查询的问题不是左连接(实际上是确定的),但是你指定树类型必须很难,所以你要删除左连接给你的空树的行。

答案 1 :(得分:0)

这适合你吗?

select p.id, p.plant, t.id as tree_id, t.type from plants p left join trees t ON (p.id = t.id) WHERE t.type = 'hard'

答案 2 :(得分:0)

SELECT p.id, p.plant
FROM plants AS p
LEFT JOIN trees AS t ON p.id = t.id
WHERE t.type = 'hard'
   OR t.type IS NULL