MySQL: Using Count to limit results? - mysql

Hi: I need a way to limit the results of a query with SUM or COUNT as if using limit. Is this possible? I have a table with questions and answers. Each entry is identified with "0" if question or "1" if response. Each answer have the questionID, so I can order by this field. I want to show the first 20 questions with all his answers without using limit, because using LIMIT 0,20 would be showing the first 20 entries no matter if they are questions or answers.
I would like to see some logic like this:
SELECT *, SUM(IF(level = '0', 1,0)) AS MyCount FROM table
WHERE MyCount<20 ORDER BY questionID,timestamp
how could I accomplish this? Any suggestion is appreciated.

Since you're doing a GROUP function (sum), try using HAVING instead of WHERE:
SELECT *, SUM(IF(level = '0 ', 1,0)) AS MyCount
FROM table
HAVING MyCount < 20
ORDER BY
questionID,timestamp
-- Edit --
Because you are storing two different types of data (response and question) in the same table, you can try a self join (untested):
SELECT
question.id AS question_id,
question.name AS question_name,
response.id AS response_id,
response.name AS response_name
FROM
table AS question
JOIN
table as response
ON
question.id AND response.level = 1
WHERE
question.level = 0;

this sounds like a badly designed schema. have your questions in one table and your answers in another, make the question ID a foreign key on the answer table. chucking both of them together in the same table is why you now have this problem!

Related

How to get data from multiple tables using just one single query?

I have a conception problem I think, not a code problem, I have 4 tables in my database, QUESTION, INTERESTS, QUESTIONTAG, and a USER.
My tables structure :
INTEREST -- id
-- user
-- tagparent
QUESTION_TAG -- id
-- tagparent
-- tagchild ( unnecessary )
-- question
QUESTION -- id
-- content and when published ( unnecessary )
I want to get 10 questions ordered by index_order ( field ) and are interesting for the USER, and I know he is interested by those questions using QUESTION_TAG association table that links between the question and the tag.
so the logic is this :
request 0 : SELECT * FROM QUESTION WHERE id = ( results of request 1
- returns many ) ORDER BY index_order LIMIT 0,10
This request must return many results :
request 1 : SELECT DISTICNT question FROM question_tag WHERE tagparent
= ( results of request 2 - returns many )
This request returns many results too
request 2 : SELECT tagparent FROM interests WHERE user=9
So using SubQueries is not really that helpful.
I am stuck, and I wish I can find a solution just using a single request, without filtering the data with a back-end language.
Any help would be much appreciated.
May Be This is what you are looking for.
select question.*, distinct question_tag.question, interests.tagparent
from question
inner join question_tag on question_tag.question = question.id
inner join interests on interest.tagparent = question_tag.tagparent
where interests.user = 9

How can i delete duplicates rows in mysql retaining the one which is having some other fields filled?

I have a table in the format :
NAME__TELEPHONE__MONTH___YEAR
aaa______2222_________jan______2018
bbb______2222________ _____________
aaa______2222___________ ___________
Here i want to check for duplicate Telephone entries and delete all except the one which is having the month and year fields filled.
Since i am not very good in join queries any help is appreciated.. i found similar kind of question but using that i couldnt retain the one which has got other filed filled.
Thankyou in advance if anyone can help.
I find out that the best answer is not delete, just move to other table, is faster and less dangerous, like this:
INSERT INTO tempTableName(id,name,telephone,month,year)
SELECT DISTINCT id,name,telephone,month,year
FROM tableName;
Hope it works!
Why not just do this?
delete t from table t
where month is null and year is null;
Try this :
delete from table t
inner join
(select name,Telephone ,row_number() over (partition by name,Telephone order by month,year ) RN
from table
) temp
on t.name = temp.name and
t.Telephone = temp.Telephone
where RN > 1

MySQL joining table to itself and comparing results

MySQLFiddle here: http://sqlfiddle.com/#!2/15d447/1
I have a single table I am trying to work with:
Table 1: user_answers table (stores users answers to various questions)
The notable values that are stored are the users id (column uid), the question id for the question they are answering (column quid), the answer to the question (column answer) and the importance of their answer (column importance).
The end result I want:
I'd like to be able to grab all the questions that any two users have answered, excluding any answers from questions that have either not been answered by the other party, or answers to the same question which have a value of 1 for either user in importance. Again, this will only ever be used to compare two users at a time.
I've been pretty unsuccesful in my attempts, but here is what I've tried, just piecing things together:
#attempt one: trying to exclude answers that were not answered by both users
SELECT * FROM user_answers AS uid1
JOIN user_answers AS uid2 ON uid1.uid = uid2.uid
WHERE uid1.uid = 1
AND uid2.uid = 20008
AND uid1.quid IS NOT NULL
AND uid2.quid IS NOT NULL;
This returns no results but I'm not exactly sure why.
#attempt two: trying to exclude where answers are the same for both users
SELECT * FROM user_answers AS uid1
LEFT JOIN user_answers AS uid2 ON (uid1.uid = uid2.uid AND uid1.answer <> uid2.answer)
This gives me results, but seems to be doubling up on everything because of the join. I also tried in this attempt to eliminate any answers what were the same, which seems to be working in that sense.
Any guidance is appreciated.
Thanks.
You can answer your question using an aggregation query. The idea is to using the having clause to filter the rows for the conditions you are looking at.
Because you are not interested at all in questions with importance = 1 those are filtered using a where clause:
select ua.quid
from user_answers ua
where importance <> 1 and uid in (1, 20008)
group by ua.quid
having sum(uid = 1) > 0 and
sum(uid = 20008) > 0;
If you want to include the answers, you can do:
select ua.quid,
group_concat(concat(uid, ':', answer) order by uid) as answers
Just a simple version of what you need.
select *
from user_answers a,
user_answers b
where a.quid = b.quid
and a.uid <> b.uid
and 1 not in (a.importance, b.importance)
If you like to filter just the questions just change the * for distinct a.quid
See it here on fiddle: http://sqlfiddle.com/#!2/15d447/15

mysql select query on two tables in specific order

I have two tables questions table like below
and answers table like below
every question has multiple answers
How can I make query to return the result as below table
You have to order by two columns - q_id and ans_id. Since in question_tb there is no ans_id field you can put 0 instead.
select t.id, t.q_content from
(
select q_id, q_content, 0 k, q_id id from question_tb
union
select ans_q_id, ans_content, ans_id, ans_id from answer_tb
) t order by t.q_id, t.k
Hmmm.. I think you need to re-think your structure a bit: the last table (or query result) needs a column to designate which is the question, and which are the answers, and also to indicate the correct answer.
Also, I assume that each set of questions (and answers) will be tied to a particular user, so you will need a user_key in the answer table, as well.
SELECT Q.q_content AS question,
ANS.ans_content AS answer,
ANS.is_correct,
ANS.user_id,
FROM Question_TB Q
INNER JOIN tb_answer ANS
ON ANS.ans_q_id = Q.q_id
ORDER BY ANS.user_id, Q.q_id

Could this MYSQL be optimized?

Hello I'm having a comments table on which I run a fulltext search.
c1 and c2 are aliases on the same table used
via criteria: c1.parent_id=0 I get the questions only(not the answers attached to them)
and via c2.parent_id<>0 I filter the questions that already have answers
SELECT DISTINCT c1.comment, c1.comment_id, MATCH(c1.comment) AGAINST ('keyword1 keyword2 keyword3') AS score
FROM comments AS c1
JOIN comments AS c2
ON c1.comment_id = c2.parent_id
WHERE c1.parent_id=0
and c2.parent_id <> 0
ORDER BY score DESC LIMIT 9
The problem is that when I run EXPLAIN SELECT... the search looks up through each and every row of the table - so the bigger it gets the slower this operation will be, instead of searching just the rows with parent_id=0.
I would like to ask: is it possible to optimize this kind of query any further?
add an index to all the id columns
alter table your_table add index(parent_id)
same with comment_id