[英]How do I always pull data from one table, but also pull data from a second table if it's there in MySQL?
Here are my two tables: 这是我的两张桌子:
oasis 绿洲
+-----+-------+
| id | title |
+-------------+
| 234 | a |
| 235 | b |
| 236 | c |
+-----+-------+
user_collection user_collection
+----+---------+----------+------+
| id | oasisid | username | data |
+--------------+----------+------+
| 1 | 234 | joe | blah |
| 2 | 235 | bob | blah |
| 3 | 236 | ted | blah |
+----+---------+----------+------+
Here's my query: 这是我的查询:
SELECT *
FROM oasis
JOIN user_collection ON oasis.id = user_collection.oasisid
WHERE username = 'greg'
AND oasis.id = '234'
What I want to do here is pull everything from oasis and user_collection that match, but also pull the information from oasis even if there is NO match on user_collection . 我想在这里做的是从绿洲和user_collection那场比赛拉的一切,而且还拉离绿洲的信息即使在user_collection不匹配。
How do I fix my query to accomplish this? 我该如何解决查询问题呢?
That's what the manual says, just to stick to MySQL... "If there is no matching row for the right table in the ON or USING part in a LEFT JOIN, a row with all columns set to NULL is used for the right table. You can use this fact to find rows in a table that have no counterpart in another table: 这就是手册所说的,只是坚持使用MySQL ...“如果在ON或LEFT JOIN的USING部分中没有正确的表匹配行,则将所有列设置为NULL的行用于正确的表您可以使用此事实在一个表中查找在另一个表中没有对应项的行:
SELECT left_tbl.*
FROM left_tbl LEFT JOIN right_tbl ON left_tbl.id = right_tbl.id
WHERE right_tbl.id IS NULL;"
http://dev.mysql.com/doc/refman/5.0/en/join.html http://dev.mysql.com/doc/refman/5.0/en/join.html
It also makes it clear, why to move the username criteria from the where clause to the ON clause, as Andrew says... 这也很清楚,为什么要将用户名条件从where子句移动到ON子句,就像Andrew所说的...
You want a left join
, but you have to be careful about the conditions in the where
clause. 您需要left join
,但是必须注意where
子句中的条件。 Conditions on the second table need to be in the on
clause for the left join
to work: 为了使left join
正常工作, 第二个表上的条件必须位于on
子句中:
SELECT *
FROM oasis JOIN
user_collection
ON oasis.id = user_collection.oasisid and user_collection.username = 'greg'
WHERE oasis.id = '234';
Conditions on the first table should go in the where
clause. 第一个表上的条件应放在where
子句中。
SELECT s.ome
, c.olumns
FROM table1 s
LEFT
JOIN table2 c
ON c.some_id = s.some_id
AND c.some_column = 'one thing'
WHERE s.some_other_column = 'another thing'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.