combining two select queries from the same table - mysql

I need to do something like this:
id tag status user trial Value (other columns)...
1 A Pass peter first 0
2 A Pass peter second 1
3 A Fail peter third 3
4 B Pass peter first 4
5 B Pass peter second 5
6 B Pass peter third 6
select the rows that tag equal A and status equal to Pass and find the same value for other tag ex:B
id tag status user trial Value_tag_A Value_tag_B (other columns)...
1 A Pass peter first O 4
2 A Pass peter second 1 5
I can do some processing using php to get this result, but i'm wondering if i can do it directly using sql
I've tried numerous variations and can't seem to get close to the result.
Solution: http://sqlfiddle.com/#!9/e9068d/17

I don't know why in the rows where tag=A also have Value_tag_B. I will ignore this and maybe the following query is an approach.
SELECT DISTINCT y.status, y.`user`, y.trial,
(SELECT Value FROM toto WHERE y.`user` = `user` and y.trial = trial and tag = 'A' ) AS Value_tag_A,
(SELECT Value FROM toto WHERE y.`user` = `user` and y.trial = trial and tag = 'B' ) AS Value_tag_B
FROM toto y
WHERE y.trial NOT IN (SELECT DISTINCT trial FROM toto WHERE `status` <> 'Pass')
The code has been modified.
SQL Fiddle

Related

Different entries within 5 seconds

Sorry I don't know how to describe the topic.
i have a database where i store the unixtime of the entries and some other stuff, in this case the column "name" for the user and "type" it can be 1 or 2.
I want to check if there are entries where name is the same and type switches from 1 to 2 and back to 1 or 2 1 2 within 5 seconds.
So it shows me something like this:
Unixtime Name type
1550293559 Peter 2
1550293560 Peter 1
1550293561 Peter 2
Is there a query that can help me do this?
Sorry I really hope you guys understand that, I don't know how to explain the problem properly.
Thanks.
You can do that with a 3x self join on that table and the necessary conditions (All 3 rows have the same name etc.). See http://www.mysqltutorial.org/mysql-self-join/ for more info.
Note that as the join produces all the possible permutations as input material, you don't have to 'permute' the conditions in the where part of the query. E.g. To get the 5 second rule, you can just say
... where e1.unixtime > e2.unixtime and e2.unixtime > e3.unixtime and e3.unixtime+6 > e1.unixtime ...
Edit: since the original answer was downwoted, here is the full query (grumble grumble) assuming the table name 'sotest':
SELECT
*
FROM
sotest e1
JOIN
sotest e2
JOIN
sotest e3
WHERE
(e1.name = e2.name AND e2.name = e3.name
AND e1.unixtime > e2.unixtime
AND e2.unixtime > e3.unixtime
AND e3.unixtime + 6 > e1.unixtime)
AND ((e1.type = 1 AND e2.type = 2
AND e3.type = 1)
OR (e1.type = 2 AND e2.type = 1
AND e3.type = 2))

MySQL query to gather incorrectly stored data

I have recently taken over a email campaign project and need to generate a report for the customer. However the data has been stored very strangely.
Basically the client wants a report of the subscribers first name and last name that have subscribed to a emailing list.
Example table data.
------------------------------------------------------------
id | owner_id | list_id | field_id | email_address | value
------------------------------------------------------------
1 10 1 137 me#example.com John
2 10 1 138 me#example.com Doe
So as you can see, John Doe has subscribed to mailing list 1, and field_id 137 is his first name and field_id 138 is his last name.
The client is looking for a export with the users first name and last name all is one field.
I tred the following sql query
SELECT value
FROM Table_A AS child
INNER JOIN Table_A AS parent
ON parent.email_address = child.email_address
WHERE child.owner_id = '10'
But unfortunately the query gives me the results in many rows but not appending the first name and last name into one field,
If anyone can provide some assistance that would be awesome.
Thanks.
SELECT
concat( parent.value,' ',child.value)name
FROM mytable AS child
left JOIN mytable AS parent
ON parent.email_address = child.email_address
WHERE child.owner_id = '10'
and parent.field_id=137 and child.field_id=138
Check at-http://sqlfiddle.com/#!9/199b4b/45
I think you have to use a variable to put in there everything you have to and then select the variable with the desired name of yours.
For example:
DECLARE #yourvariable VARCHAR(MAX)
SELECT #yourvariable = COALESCE(#yourvariable + " ") + value
FROM table_A
WHERE owner_id = 10
SELECT #yourvariable as FullName
Try that, it might help.
You can try this code(column name equals value in your original DB):
select a.name
from
table_a a inner join table_a b
on a.email_address = b.email_address and a.field_id <> b.field_id
where a.owner_id=10
order by a.field_id
Here is the example link:
http://sqlfiddle.com/#!9/5fbdf6/25/0
As per assumptions, first name has the field id 137 and last name has the field id 138.
You can try the following query to get the desired result.
SELECT CONCAT(SUBSTRING_INDEX(GROUP_CONCAT(`value`),",",1)," ",SUBSTRING_INDEX(GROUP_CONCAT(`value`),",",-1)) AS client_name
FROM Table_A
WHERE owner_id = 10
AND field_id IN (137, 138)
GROUP BY email_address;

Joining 2 tables that use LIKE as a common identifier

I have two tables.
wp_rg_lead_detail:
id lead_id form_id field_number value
=====================================================
166649 2579 4 235 batman
167324 2602 4 235 batman
168439 2579 4 235 kelsey
169221 2836 4 235 batman
wp_rg_incomplete_submissions:
uuid form_id submission
=======================================================================
fds4389dsd2kjd 4 JSON entry that doesn't contain 'kelsey
ciwod2938slsck 4 JSON entry that contains 'kelsey
392copaa234jfl 4 JSON entry that doesn't contain 'kelsey
What I want to do is grab the record that:
has the word 'kelsey' in wp_rg_incomplete_submissions.submission
has a wp_rg_incomplete_submissions.form_id of 4
has the word 'kelsey' as a value in wp_rg_lead_detail
and the lead_id for that entry in wp_rg_lead_details should also have the word 'batman' for a value.
The only identifier between the two tables is the word 'kelsey'. But where it exists in wp_rg_lead_detail, that lead_id must also have an entry with the value of 'batman'.
I have tried subqueries and joins, and I'm getting nowhere. Can someone please point me in the right direction?
UPDATE
From the feedback below, it sounds like I should create an alias and then join them where that exists in both. Here's where I'm at:
SELECT *, 'kelsey' AS myvalue
FROM `wp_rg_lead_detail`
WHERE (`value` LIKE 'batman'
OR `value` LIKE 'kelsey')
AND `form_id` = 4
GROUP BY `lead_id`
HAVING count(*) > 1
I think somehow I need to join this where the LIKE uses myvalue:
SELECT *, uuid
FROM `wp_rg_incomplete_submissions`
WHERE `form_id` = 4
AND `submission` LIKE concat_ws(";", "%", myvalue, "%")
UPDATE #2
After continuing to struggle with this, I've come up with:
SELECT *
FROM wp_rg_lead_detail
INNER JOIN wp_rg_incomplete_submissions ON wp_rg_lead_detail.value
LIKE CONCAT('%', wp_rg_incomplete_submissions.submission, '%')
WHERE wp_rg_lead_detail.value = 'kelsey'
I know I'm doing something wrong because there are no results. But I feel it is much closer than where I started from.
So here is what I came up with, not vouching for it's efficiency as I don't write much SQL.
SELECT *
FROM submissions
JOIN (SELECT detail.*
FROM detail
JOIN detail detail2
ON detail2.lead_id = detail.lead_id
WHERE detail.value = 'kelsey'
AND detail2.value = 'batman'
) as detailjoin
ON detailjoin.form_id = submissions.form_id
WHERE submissions.submission LIKE '%kelsey%'
AND submissions.form_id = 4;
Which from you data set returns:
'ciwod2938slsck' 4 'JSON with kelsey' 168439 2579 4 235 'kelsey'
So to break it down, the inner join query gets all detail rows that have 'kelsey' as a value where that lead_id also exists in a row with a 'batman' value.
The outer query selects all rows with form_id of 4 and 'kelsey' in submission
Then it simply joins the two on form_id = form_id.
I believe this does what you needed although with the small data set not positive.

Do a while in a query, subquery

I want do query that show data of some users bat, first is a other query, is something difficult of explain. i dont want get the data of the users that me follow, i want see data that me don't follow. So i have two table "follow_follower", "user" and now do a middle query but doesn't match:
follow_follower
cod seguidor seguido
1 1 2
2 1 3
3 1 8
4 1 6
5 8 2
6 2 8
7 2 4
8 3 2
9 5 1
User
cod nombre apellido telefono
1 carlos cardenas 12587
2 Umberto Contreras 125488
3 carlos Torres 44587
4 Victor Sambrano 69754
5 Carlos Barragan 3698741
6 Jorge Cantor
7 Umberto Zanetty 578825
8 Miguel Cantor 5488787
ok and if you see are four fields in follow_follower that the user is 1 (Carlos Cardenas), how do query that first get all user that me follow and after select all data of people diferent "DISTICN" see my query:
select distinct(nombre), apellido, telefono
FROM usuario
where cod<> ANY(select seguido from follow_follower where seguidor=1)
order by cod
But only DISTINC a ANY row of all query.
ok i want a list little of people that me don't follow but i see your query and show error, i know little of mysql query ADVANCE :( and the other problem is that my db is write in spanish... but go to try the table db like are!!! :
this is a the true query:
SELECT distinct(usua.cod), usua.nick, desi.usuario, main.dir, main.size, main.x, main.y, main.R, main.G, main.B, main.A
FROM usuario AS usua, design AS desi, mainPhoto AS main
WHERE desi.usuario = usua.cod
AND desi.cod = main.design
AND usua.cod <> ANY(select seguido from seguidor_seguido where seguidor=1)/**!!!!!/
AND main.dir <> ''
AND main.type =1
ORDER BY usua.nick DESC
LIMIT 44 , 6
so the unique table that true import are usuario (content data of user) and seguidor_seguido(content all the records follow)
---describe table seguidor_seguido:
seguidor_seguido
cod // is the id of the record
seguidor // is the user that follow to other users
seguido // is the user that is followed by other users
Although the request is different from the original is the same problem!!!
thanks :D
Sounds like you want a list of all users that don't follow you. I'm not sure if you want that to be transitive or not (i.e., including users that follow users that follow you, etc.).
If you just want to do it one level deep, it'll go like this. You want to get a list of all entries in the follow_follower where the seguido (I assume that's supposed to mean "person who is being followed") is not you. Users can follow other people, but they can't follow you. You can join twice against the User table to get user names.
SELECT DISTINCT
usuario_seguidor.nombre,
usuario_seguidor.applido,
usuario_seguidor.telephono
FROM follow_follower
JOIN usuario AS usuario_seguidor
ON usuario_seguidor.cod = follow_follower.seguidor
WHERE follow_follower.seguido <> 1
I could finally end the query and match ok!! :D see:
SELECT U.cod, U.nombre, U.apellido, U.telefono FROM User U LEFT JOIN (SELECT f.seguido
FROM follow_follower f
WHERE f.seguidor = 1)t1 ON u.cod = t1.seguido
WHERE t1.seguido IS NULL AND U.cod <> 1 GROUP BY U.cod
this is the query that me need, but i thanks :D

How do I compare two queries by two columns in MySQL?

What's the best way to compare two queries by two columns? these are my tables:
This table shows exam questions
idEvaluation | Question | AllowMChoice | CorrectAnswer|
1 1 0 3
1 2 1 4
1 2 1 5
1 3 0 9
This table shows a completed exam
idExam| idEvaluation | Question | ChosenAnswer|
25 1 1 2
25 1 2 4
25 1 2 5
25 1 3 8
I have to calculate the percentage of correct Answers, considering to certain questions may allow multiple selection.
Correct Answers / Total Answers * 100
thanks for your tips!
This code will show you a listing of Questions and whether or not they were answered correctly.
select
A.Question,
min(1) as QuestionsCount,
-- if this evaluates to null, they got A) the answer wrong or B) this portion of the answer wrong
-- we use MIN() here because we want to mark multi-answer questions as wrong if any part of the answer is wrong.
min(case when Q.idEvaluation IS NULL then 0 else 1 end) as QuestionsCorrect
from
ExamAnswers as A
left join ExamQuestions as Q on Q.Question = A.Question and Q.CorrectAnswer = A.ChosenAnswer
group by
A.Question -- We group by question to merge multi-answer-questions into 1
Output Confirmed:
Note, the columns are intentionally named this way, as they are to be included as a subquery in part-2 below.
This code will give you the test score.
select
sum(I.QuestionsCorrect) as AnswersCorrect,
sum(I.QuestionsCount) as QuestionTotal,
convert(float,sum(I.QuestionsCorrect)) / sum(I.QuestionsCount) as PercentCorrect -- Note, not sure of the cast-to-float syntax for MySQL
from
(select
A.Eval,
A.Question,
min(1) as QuestionsCount,
min(case when Q.idEvaluation IS NULL then 0 else 1 end) as QuestionsCorrect
from
ExamAnswers as A
left join ExamQuestions as Q on Q.Question = A.Question and Q.CorrectAnswer = A.ChosenAnswer
where
A.Eval = 25
group by
A.Question, A.Eval) as I
group by
I.Eval
Output Confirmed:
This will communicate the general concept. Your column names idEvaluation and Eval are difficult for me to understand, but I'm sure you can adjust the code above to suit your purposes.
Note, I did this in sql server, but I used fairly basic SQL functionality, so it should translate to MySQL well.