Select result from table for matching 2 rows in mysql - mysql

I have a MySQL table has these fields
ID, CID, QUESTION, ANSWER, USER
ID is auto increment, every record in table has ID;
CID is point to ID for ANSWER records
For example, we have 4 records, 2 of question 2 of answer, and Mike answers 2 questions
ID CID QUESTION ANSWER USER
1 0 Test NULL John
2 1 NULL This is Test Mike
3 0 Example NULL Tracy
4 3 NULL Yes it is Mike
I want to list questions of which is Mike's answers. How can I match ID and CID fields in same table and print QUESTION for output

I want to list questions of which is Mike's answers.
SELECT t1.*
FROM TableName t1
LEFT JOIN TableName t2 ON t1.ID = t2.CID
WHERE t2.Answer IS NOT NULL
AND t2.User = 'Mike';
SQL fiddle Demo
Note that this gives you the list of questions that Mike has answered therefore you won't find mike listed on them:
ID CID QUESTION ANSWER USER
1 0 Test NULL John
3 0 Example NULL Tracy

select QUESTION from yourtable
where ID in(select ID from yourtable where User = 'Mike' and answer is NOT NULL)

Related

Query database to obtain first unique value

I have a pretty simple table like this:
id | custom_id | answer
----------------------------------
1 | 123 | Answer 1
__________________________________
2 | 123 | Answer 2
__________________________________
3 | 422 | Answer 3
__________________________________
4 | 345 | Answer 2
__________________________________
5 | 992 | Answer 1
__________________________________
6 | 452 | No answer
__________________________________
What I am trying to do is count the number of Answer 1, Answer 2, etc. So, for the above data I would expect to get:
2 * Answer 1
2 * Answer 2
1 * Answer 3
Note, that anything that is No answer should be discarded.
However, further to the above, I want to take into account only one answer per custom_id, and this should be their first answer. So really, the output I expect to get for the above data should be:
2 * Answer 1
1 * Answer 2
1 * Answer 3
This is because we take only the first answer for custom_id = 123.
So far, I have made the following query:
select
answer,
count(*) as totalCount
from
" . DB_TABLE . "
where
answer <> 'No answer'
group by
custom_id
However, this seems to return the total counts (as I explained first), not taking into consideration that there should only be one per custom_id. I thought the group by would solve this issue, but this does not seem to be the case.
How can I achieve the results I am after?
Thanks
One approach, will be first to create a derived table with the IDs of the first answers for every custom_id and also filter those with values No answer (since you want to ignore they), like this:
SELECT
custom_id,
MIN(id) AS firstAnswerID
FROM
<table_name>
WHERE
answer <> "No Answer"
GROUP BY
custom_id
Then, we can join the original table with this previous one on the ID column (this will act like a filter for those that aren't first answers or have the No answer value), make a GROUP BY the answer column and count the numbers of each one. In summary, this will do what you want:
SELECT
t1.answer,
COUNT(*) AS NumTimes
FROM
<table_name> AS t1
INNER JOIN
( SELECT
custom_id,
MIN(id) AS firstAnswerID
FROM
<table_name>
WHERE
answer <> "No Answer"
GROUP BY
custom_id ) AS t2 ON t2.firstAnswerID = t1.id
GROUP BY
t1.answer
ORDER BY
NumTimes DESC
You can play with this here: DB Fiddle
Try to use this:
select answer, count(answer) as totalCount from " . DB_TABLE .
" where answer <> 'No answer' group by answer
You should count rows for every answer group, not for the entire table.

MySQL: update by selection condition

I have system of questions and answers,
each question should have 4 answers
I need to run SQL query to update question's "class" to be "D" (to prevent it from appear) if it has less than 4 answers
tables structures:
question (table)
id text class
1 Is.. A
2 Where.. B
3 where.. A
4 Why.. A
5 Do.. A
answer (table)
id qid text
1 1 ..
2 1 ..
3 1 ..
4 2 ..
5 3 ..
note: "answer.qid" refer to "question.id"
thanks,
Try something with subquery like:
UPDATE question
SET class = 'D'
WHERE id IN
(SELECT qid
FROM answer
GROUP BY qid
HAVING count(qid) < 4)
On the fly I would say, you could use a subselect:
UPDATE question SET class='D' WHERE ( SELECT count(*) FROM answer INNER JOIN answer.qid = question.id ) < 4;
update question
set class='D'
where question.id in (select qid from answer group by qid having count(*)<4)

select query for multiple chat system [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm making a system of chat similar to facebook, where you can talk with 2 or 3 people in the same time. My issue is on the select the conversation.
inbox_conversation (this table is for create a new id of conversation if the user start to talk the first time)
id_conversation | occured_at
1 13482942
2 18583953
inbox_join (table for user join on the conversation in this case there is user 1, 2, 3 on the disccussion with id 1)
id_conversation | id_user
1 1
1 2
1 3
2 4
2 5
inbox_msg (table for record the message sent)
id_conversation | id_user | message | occured_at
1 1 Hey 1457694
1 2 Hola 3848374
1 3 Cool 3294933
2 4 Wow 4392934
2 5 Yes 9485737
Now i have to do some query for select the messages having just the id_user of the conversation, in this case i have 1,2,3. Someone can help me to build this query please.
Final result that i'm looking for selecting the discussion with id_user 1,2,3
id_user | message | occured_at
1 Hey 1457694
2 Hola 3848374
3 Cool 3294933
PS: if the conversation have 3 users and i try to select just 2 of them i have be able to don't see the conversation.
if I have just the id of the users 1,2 in this case there is no discussion with just that 2 user, but if the user 1 write to user 2 in the database will be another id discussion and will correlate to both user. Like that if i add another user example user 3 he can't see the previous messages sent between user 1 and 2
if is a bad idea select just with id user, i can study some solution for pass the id of discussion.
ok, i did came up with logic for something called "Dataset Comparison" where multiple datasets of multiple rows were getting compared and need to find if any of them are matching.
basic point in this query will be, durig the search we need to make sure that the session we find out has exactly same user by value and by count. (nothing more+nothing less+same value)
DECLARE #inbox_msg TABLE
(
id_conversation INT NOT NULL
,id_user INT NOT NULL
,[message] NVARCHAR(MAX) NULL
,occured_at TIMESTAMP NOT NULL
)
INSERT INTO #inbox_msg
( id_conversation ,
id_user ,
message
)
SELECT 1,1,'Hey'
UNION ALL SELECT 1,2,'Hola'
UNION ALL SELECT 1,3,'Cool'
UNION ALL SELECT 2,4,'Wow'
UNION ALL SELECT 2,5,'Yes'
--this I added to make sure 3 will not become part of your result set.
UNION ALL SELECT 3,1,'Testing'
UNION ALL SELECT 3,2,'Search'
UNION ALL SELECT 3,3,'query'
UNION ALL SELECT 3,4,'Result'
--this is the list of users you want to search for
DECLARE #searchMessgeByUser TABLE
(
id_user INT NOT NULL PRIMARY KEY
)
INSERT INTO #searchMessgeByUser ( id_user )
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
--find out the sessionID who has exactly same number of user as participant as requested
DECLARE #MatchedSessionID TABLE
(
id_conversation INT NOT NULL
)
INSERT INTO #MatchedSessionID( id_conversation )
SELECT qry.id_conversation
FROM
(
--find out the MatchedSessionIDByUserCount
SELECT id_conversation
FROM #inbox_msg
GROUP BY id_conversation
HAVING (COUNT(DISTINCT id_user) = (SELECT COUNT(1) FROM #searchMessgeByUser) )
INTERSECT
--find out the MatchedSessionIDByUserValue
SELECT id_conversation
FROM #inbox_msg msg
JOIN #searchMessgeByUser usr
ON msg.id_user=usr.id_user
GROUP BY msg.id_conversation
)qry
--final Query
SELECT id_user,message,occured_at
FROM #inbox_msg
WHERE id_conversation IN (SELECT id_conversation FROM #MatchedSessionID)
ORDER BY occured_at
the questions are bit unclear so just making clear what exactly you need?
In the start you mentiuoned that result is queried based on ID_User only.
But in the example last you have is saying "...the result is for DiscussionID 1"
so whihc one is correct? Does DiscussionID and ID-User both available to filter or not?
Also, "PS: if the conversation have 3 users and i try to select just 2 of them i have be able to don't see the conversation"
is that mean id_User filter is of type "WHER ID_USER IN ('','','',)"

Find the oldest record in a join between two tables

I have two tables. "Questions": A list of questions, "Results" The users results to these questions.
Table: Questions
ID
Table: Results
ID
Created - When this record was added.
Q_ID - A FK to the Question table
Example data
Table: Questions
ID
----
1
8
15
55
Table: Results
ID | Created | Q_ID
--------------------
1 | 12:02 | 1
2 | 12:03 | 15
3 | 12:04 | 8
I am looking for a query (or two) that will get me the following information.
A question that does not have a result associated with it.
If all questions have results then find the question with the oldest result.
This query should return question.id=55, because its is the only question that does not have a result. If question.id=55 did not exist then it would return question.id=1 as it has the oldest result to the question.
If you LEFT JOIN the two tables, you can use the ORDER BY clause to do what you need:
SELECT *
FROM
questions
LEFT JOIN results
ON results.q_id = questions.id
ORDER BY
ISNULL(results.id) DESC, results.created ASC
LIMIT 1
This will place any questions that do not have results at the top of the list, followed by a list of all questions with results (in "oldest question first" order). The LIMIT 1 will have it display only the top result - which should match what you need.
1- A question that does not have a result associated with it
select q.qid from questions q where q.qid not in ( select r.qid from result r )
2- find the question with the oldest result
select min(r.createdon) from result r

most common tags amongst selected table items?

I have a table similar to below
Questions table:
Qid Tags
--- ---------
1 SQL
1 DATABASE
1 ALGORITHM
2 ALGORITHM
2 TAGS
3 SQL
3 SYNTAX
3 DATABASE
The following
SELECT * FROM Question table WHERE TAGS='SQL'
will display:
Qid Tags
--- ----
1 SQL
2 SQL
3 SQL
I'm looking for a query which will display the highest related question based on similar tags.
So if I looked up Question table - Qid=1. The result would be Qid 3, as Qid 1 and Qid 3 have 2 similar terms, but Qid 2 only as 1 similar tag to Qid 1. If i looked up Qid 2 it would return Qid 1 as it they share 1 tag and Qid 2 and 3 share no tags. And If i looked up Qid 3 it would return Qid 1 as it as Qid 1 has 2 tags that Qid 3 has, but Qid 2 has no tags that Qid 3 has.
Thanks for any help.
Something along these lines maybe?
SELECT Qid, COUNT(*) AS TagsInCommon FROM Questions
WHERE Tags IN (
SELECT DISTINCT Tags FROM Questions WHERE Qid=1
)
GROUP BY Qid
ORDER BY TagsInCommon DESC
I'm not sure about the field names but you get the idea...
declare #Qid int
set #Qid = 1
select top 1 Q2.Qid, COUNT(*) from Questions Q1
inner join Questions Q2 on Q1.Tags = Q2.Tags
where Q1.Qid = #Qid and Q2.Qid <> #Qid
group by Q2.Qid
order by COUNT(*) desc