0

I have following table structure and data:

+-----------+-------+
|type | value |
+-----------+-------+
|first_name | john |
+-----------+-------+
|last_name | doe |
+-----------+-------+
|last_name | smith |
+-----------+-------+

I need to get count (in my case it's 1), if table contain data John Doe. Query like:

SELECT COUNT(*) FROM tablename WHERE (type='first_name' AND value='john') AND (type='last_name' AND value='doe')

returns zero count. Don't understand, how to create this combined query.

asked Apr 25, 2020 at 3:10
4
  • 1
    your where clause is evaluated per row. So you cannot have a type=first_name and type=last_name both true at the same time (hence 0 rows). How do you the difference between john doe and john smith? EAV is painful and this is the wrong way to do it. Commented Apr 25, 2020 at 3:21
  • thank you @danblack, so. there is no way to keep my current structure? Commented Apr 25, 2020 at 13:13
  • There is no relation in the data between first and last name. So it can't be done with the current structure. Structure are there to make queries easy. Change your structure for a first_name, last_name columns and it be very easy. Welcome to DBA stackexchange. Commented Apr 25, 2020 at 22:44
  • @danblack check my answer Commented May 5, 2020 at 19:17

1 Answer 1

0

I think I found the solution for this case. My solution is to use SUM() aggregation with IF() condition. The final logic is substitute COUNT(*) to boolean - have rows or empty query. This query will return results only if it match both conditions:

SELECT SUM(IF((value='john' AND type='first_name') OR (value='doe' AND type='last_name'), 1, 0)) AS cnt FROM tablename HAVING cnt=2;

If I want to select all data where first name is John and last name is Doe OR last name is Smith, query will be:

SELECT sum(IF((value='john' AND type='first_name') OR (value='doe' AND type='last_name'), 1, 0)) AS first_last, SUM(IF(value='smith' AND type='last_name', 1, 0)) AS last FROM tablename HAVING first_last=2 OR last=1;

answered May 5, 2020 at 19:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.