MySQL Left join WHERE table2.field = “X”

2020-05-30 06:22发布

I have the following tables:

pages:

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| page_id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| type       | varchar(20)  | NO   |     | NULL    |                |
| categories | varchar(255) | NO   |     | NULL    |                |
| title      | varchar(255) | NO   | MUL | NULL    |                |
| text       | longtext     | NO   | MUL | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

custom:

+---------+------------------+------+-----+---------+-------+
| Field   | Type             | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+-------+
| page_id | int(10) unsigned | NO   | PRI | NULL    |       |
| key     | varchar(255)     | NO   | PRI | NULL    |       |
| value   | longtext         | NO   |     | NULL    |       |
+---------+------------------+------+-----+---------+-------+

I want to join the tables in a way where:
1) all the entries from the first table are returned LEFT JOIN custom ON pages.page_id = custom.page_id
2) pages.type IN ('type_a', 'type_b', 'type_c')
3) "key" from the second table has value "votes" custom.key = 'votes'

I made everything so far, but the third condition is the problem. If there isn't entry for key = 'votes' in table custom the query returns only these with entries. I want to return NULL if missing entries.

I need key = 'votes', because I have other entries for this page_id where the key is not 'votes' and this duplicates the rows from pages

3条回答
迷人小祖宗
2楼-- · 2020-05-30 06:35

try changing your where condition to custom.key = 'votes' OR custom.key is null.

查看更多
Melony?
3楼-- · 2020-05-30 06:52

Simply add your contraint custom.key='votes' to the LEFT JOIN

SELECT * 
FROM pages LEFT JOIN custom 
     ON pages.page_id=custom.page_id AND custom.key='votes' 
WHERE pages.type IN('type_a','type_b','type_c') ;
查看更多
萌系小妹纸
4楼-- · 2020-05-30 06:55

I'd do it like this:

SELECT * 
FROM pages 
LEFT JOIN
   ( SELECT * From custom where key='votes') cv
   on pages.page_id = cv.page_id
WHERE pages.type IN ('type_a', 'type_b', 'type_c');
查看更多
登录 后发表回答