Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding one row from pivot table

Tags:

sql

mysql

I have two tables called conversations and users they are bound with the pivot table conversation_user which contains a user_id and a conversation_id column.

| conversation_id | user_id |
|-----------------|---------|
|               1 |       1 |
|               1 |       2 |
|               2 |       1 |
|               2 |       2 |
|               2 |       3 |

I want to send the database some user ids and retrieve the conversation they are in together.

For example:

When I send 1 and 2 i must receive the conversation_id 1, when I send 1, 2 and 3 i must receive the conversation_id 2.

How may I write a such query?

like image 568
Ozan Kurt Avatar asked Dec 14 '15 09:12

Ozan Kurt


People also ask

How do I select certain rows in a PivotTable?

Once the Enable Selection feature has been turned on, you can use the Selection Arrow to select specific sections of an Excel Pivot Table. When the pointer changes to a thick black arrow, click, to select the row labels for that field.

How do I show individual data in a PivotTable?

In the PivotTable, right-click the value field, and then click Show Values As. Note: In Excel for Mac, the Show Values As menu doesn't list all the same options as Excel for Windows, but they are available. Select More Options on the menu if you don't see the choice you want listed.


1 Answers

You can use GROUP BY and HAVING:

SELECT conversation_id 
FROM tab                     -- subquery/temp table/whatever
GROUP BY conversation_id 
HAVING SUM(user_id = 1) > 0
   AND SUM(user_id = 2) > 0
   AND SUM(user_id = 3) > 0
   AND SUM(user_id NOT IN (1,2,3)) = 0

SqlFiddleDemo

For 1 and 2:

SELECT conversation_id 
FROM tab
GROUP BY conversation_id 
HAVING SUM(user_id = 1) > 0
   AND SUM(user_id = 2) > 0
   AND SUM(user_id NOT IN (1,2)) = 0
like image 156
Lukasz Szozda Avatar answered Oct 26 '22 17:10

Lukasz Szozda