MySQL:植物
+----+--------+
| id | plant |
+----+--------+
| 1 | tree |
+----+--------+
| 2 | flower |
+----+--------+
| 3 | tree |
+----+--------+
MySQL:树
+----+------+
| id | type |
+----+------+
| 1 | hard |
+----+------+
| 3 | soft |
+----+------+
我想选择表格植物中的所有行。
但如果plant = tree
,那么表格树中的类型必须为hard
才能显示。
因此,上面的示例应输出:1=tree
和2=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'
关于我如何做到的任何想法?
答案 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