Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Left join WHERE table2.field = "X"

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

like image 439
Ivan Dokov Avatar asked Apr 02 '12 08:04

Ivan Dokov


3 Answers

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') ;
like image 144
dgw Avatar answered Oct 31 '22 17:10

dgw


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');
like image 34
GregHNZ Avatar answered Oct 31 '22 19:10

GregHNZ


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

like image 2
Euclides Mulémbwè Avatar answered Oct 31 '22 17:10

Euclides Mulémbwè