简体   繁体   中英

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

+----+---------+----------+------+
| 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 .

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:

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

It also makes it clear, why to move the username criteria from the where clause to the ON clause, as Andrew says...

You want a left join , but you have to be careful about the conditions in the where clause. Conditions on the second table need to be in the on clause for the left join to work:

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.

 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM