Hello I need help in writing a query.
Below is my DB structure
id name key value
1 book1 key1 abc
2 book2 key2 aaa
3 book3 key5 abc
4 book4 key3 abc
5 book5 key2 aaa
6 book6 key2 aab
7 book7 key1 abc
8 book8 key2 abc
9 book9 key1 abc
10 book10 key1 abc
And I need those books whose key has combination key1 with value abc and key2 with value aaa.
SO it should return
1 book1 key1 abc
2 book2 key2 aaa
5 book5 key2 aaa
7 book7 key1 abc
9 book9 key1 abc
10 book10 key1 abc
book having key2 and value aab wont return.
P.s This is just an example structure I have made to demonstrate my need. Actually I am working on wordpress post meta table.
I think that according to your design at some point in time you’ll have several
key+valuepairs per book. This means that you might wish to select books where several specific keys has some particular values.This can be achieved with the following SQL (for the given example):
The inner part will create a pivoted table with keys in subject, while the outer part will perform the result filtering. You can play around with this setup here.
Though, for such design, I would recommend splitting the table in subject into 2 separate ones:
booksandparams. You can observe such setup here.Note, that if you’ll change filter condition to be
k.key1='abc' AND k.key2 = 'aaa', then you’ll have onlybook10matching.This example is quite simple, but it gives the idea.