Pregunta

I've got a table PERSON_PROPERTIES that resembles the following :

|   ID   |   KEY    |    VALUE     |   PERSON_ID   |
|    1   |   fname  |    robert    |       1       |
|    2   |   lname  |    redford   |       1       |
|    3   |   fname  |    robert    |       2       |
|    4   |   lname  |    de niro   |       2       |
|    5   |   fname  |    shawn     |       3       |
|    6   |   nname  |    redford   |       3       |

I would like to SELECT (in JPQL or in PSQL) the PERSON_ID that matches the given fname and lname.

I've tried

`SELECT DISTINCT *
FROM PERSON_PROPERTIES t0
WHERE ((((t0.key = 'fname')
AND (t0.value    = 'robert'))
AND ((t0.key     = 'lname')
AND (t0.value    = 'redford'))))`

but it returns me no value.

I've also tried

`SELECT DISTINCT *
FROM PERSON_PROPERTIES t0
WHERE ((((t0.key = 'fname')
AND (t0.value    = 'robert'))
OR ((t0.key      = 'lname')
AND (t0.value    = 'redford'))))`

but this way it returns me all values. I don't know how to turn the query properly for it to give me only value 1.

¿Fue útil?

Solución

SELECT PERSON_ID
FROM PERSON_PROPERTIES
group by PERSON_ID
having sum(case when key = 'fname' and value = 'robert' then 1 else 0 end) > 0
and sum(case when key = 'lname' and value = 'redford' then 1 else 0 end) > 0

Groupy by the person and select only those having both values.

Otros consejos

Another approach would be with subselect (caution, it's MS SQL 2012)

SELECT PERSON_ID
FROM PERSON_PROPERTIES
WHERE [Key] = 'fname' AND value = 'robert'
AND PERSON_ID in 
(SELECT PERSON_ID FROM PERSON_PROPERTIES WHERE [Key] = 'lname' AND value = 'redford')

Fiddle Demo

Along with some colleagues we came to this answer :

SELECT p.PERSON_ID
FROM PERSON_PROPERTIES p
WHERE (p.key = 'fname' AND p.value = 'robert')
OR (p.key = 'lname' AND p.value = 'redford')
GROUP BY p.PERSON_ID
HAVING count(*) = 2

What do you think about it?

SELF JOIN also does the trick. DISTINCT for duplicate person_id:

SELECT DISTINCT a.PERSON_ID
FROM PERSON_PROPERTIES a JOIN PERSON_PROPERTIES b ON a.PERSON_ID = b.PERSON_ID
WHERE a.the_key = 'fname' AND a.value = 'robert'
AND b.the_key = 'lname' AND b.value = 'redford';

Demo

OK I will be marking this as the correct answer. The only thing I did was modified it a bit

SELECT Y.*, M.* FROM wp_postmeta as Y JOIN wp_postmeta AS M USING (`post_id`) 
 WHERE (Y.meta_key = 'agam_post_options_year' AND Y.meta_value = 2013) 
AND (M.meta_key = 'agam_post_options_month' AND M.meta_value BETWEEN 0 AND 12 ) 
GROUP BY Y.meta_value, M.meta_value ORDER BY M.meta_value+0 DESC

So I get that DESC order.. however.. I noticed that it does not duplicates results... I had two posts with the same year and same month... now I don't see it... is there anything there that's preventing this ?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top