SQL Joins - Gather all from RIGHT table - mysql

I have two tables:
user-data:
id | userID | keyID | val
1 99 1 1
user-data-keys
id | key
1 is-staff
2 description
3 image
Now, when I run the following SQL, I get the desired output:
SELECT `key`,`val` FROM `user-data` RIGHT JOIN `user-data-keys` ON `user-data`.`keyID` = `user-data-keys`.`id`;
Which produces:
key | val
is-staff 1
description NULL
image NULL
Which is exactly what I want. However when I add a WHERE clause to the SQL:
SELECT `key`,`val` FROM `user-data` RIGHT JOIN `user-data-keys` ON `user-data`.`keyID` = `user-data-keys`.`id` WHERE `userID` = 99;
I only get the one row with is-staff in it. Which I understand, as I asked for only rows with userID = 99. However I am planning on storing lots of different user's information in the one user-data table, and I want to know if they have a NULL value for each of the keys. So how can I achieve this? I know it's got to be some kind of fancy join that I am not aware of.
So to clarify: i need the output like this:
key | val
is-staff 1
description NULL
image NULL
When using a WHERE userID = 99. Currently I only get one row whilst using a WHERE clause.

Move the predicate from the WHERE clause to the join:
SELECT `key`,`val` FROM `user-data` RIGHT JOIN `user-data-keys` ON `user-data`.`keyID` = `user-data-keys`.`id` and `userID` = 99;

If you want to get rows which are not matched then you can add where conditions with join like " ON user-data.keyID = user-data-keys.id AND userID = 99 " instead of " WHERE userID = 99 ",
SELECT `key`,`val`
FROM `user-data`
RIGHT JOIN `user-data-keys` ON `user-data`.`keyID` = `user-data-keys`.`id` AND `userID` = 99
WHERE 1;

Related

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.

SQL unwanted results in NOT query

This looks like it should be really easy question, but I've been looking for an answer for the past two days and can't find it. Please help!
I have two tables along the lines of
texts.text_id, texts.other_stuff...
pairs.pair_id, pairs.textA, pairs.textB
The second table defines pairs of entries from the first table.
What I need is the reverse of an ordinary LEFT JOIN query like:
SELECT texts.text_id
FROM texts
LEFT JOIN text_pairs
ON texts.text_id = text_pairs.textA
WHERE text_pairs.textB = 123
ORDER BY texts.text_id
How do I get exclusively the texts that are not paired with A given textB? I've tried
WHERE text_pairs.textB != 123 OR WHERE text_pairs.textB IS NULL
However, this returns all the pairs where textB is not 123. So, in a situation like
textA TextB
1 3
1 4
2 4
if I ask for textB != 3, the query returns 1 and 2. I need something that will just give me 1.
The comparison on the second table goes in the ON clause. Then you add a condition to see if there is no match:
SELECT t.text_id
FROM texts t LEFT JOIN
text_pairs tp
ON t.text_id = tp.textA AND tp.textB = 123
WHERE tp.textB IS NULL
ORDER BY t.text_id ;
This logic is often expressed using NOT EXISTS or NOT IN:
select t.*
from texts t
where not exists (select 1
from text_pairs tp
where t.text_id = tp.textA AND tp.textB = 123
);

Dynamic Table Joining Based on Another Table Column Value?

I'm trying to figure out if there is a simple way to dynamically load a 2nd table based on the column value of the first table with mysql
Servers (Table 1):
ID | Game | Title
Servers_1 (Table 2, option 1):
server_id (links to servers.id) | game_version | players | plugins
Servers_2 (Table 2, option 2):
server_id (links to servers.id) | game_version | players | mods | game_map
Servers_etc. (Table 2, option etc.)
Trying to figure out how to do something like
left_join servers_[servers.game] on servers.id = servers_[servers.game].server_id
So it would grab the value of servers.game and use that to finish the table name. If this is not possible, then is a case statement possible such as:
Left_Join
if ( servers.game == 1 ) 'servers_1'
elseif ( servers.game == 2 ) 'servers_2'
elseif ( servers.game == 3 ) 'servers_3'
One option would be to LEFT JOIN each of the tables and use a CASE statement to return the appropriate data.
Something like this should help get you started:
SELECT S.Id, S.Game, S.Title,
CASE S.Game
WHEN 1 THEN S1.game_version
WHEN 2 THEN S2.game_version
END game_version,
...
FROM Servers S
LEFT JOIN Servers_1 S1 ON S.id = S1.Server_Id AND S.Game = 1
LEFT JOIN Servers_2 S2 ON S.id = S2.Server_Id AND S.Game = 2
Instead of using CASE, you could probably just use COALESCE as each Id/Game should be unique and only 1 wouldn't be NULL:
SELECT COALESCE(S1.game_version,S2.game_version,...) game_version
If there is no way the same server id can be in multiple tables, then you can leave the AND S.Game... out of the LEFT JOINs as it wouldn't longer be needed. Depends on your unique keys.
Alternatively, you could use Dynamic SQL.

How to use result of an subquery multiple times into an query

A MySQL query needs the results of a subquery in different places, like this:
SELECT COUNT(*),(SELECT hash FROM sets WHERE ID=1)
FROM sets
WHERE hash=(SELECT hash FROM sets WHERE ID=1)
and XD=2;
Is there a way to avoid the double execution of the subquery (SELECT hash FROM sets WHERE ID=1)?
The result of the subquery always returns an valid hash value.
It is important that the result of the main query also includes the HASH.
First I tried a JOIN like this:
SELECT COUNT(*), m.hash FROM sets s INNER JOIN sets AS m
WHERE s.hash=m.hash AND id=1 AND xd=2;
If XD=2 doesn't match a row, the result is:
+----------+------+
| count(*) | HASH |
+----------+------+
| 0 | NULL |
+----------+------+
Instead of something like (what I need):
+----------+------+
| count(*) | HASH |
+----------+------+
| 0 | 8115e|
+----------+------+
Any ideas? Please let me know! Thank you in advance for any help.
//Edit:
finally that query only has to count all the entries in an table which has the same hash value like the entry with ID=1 and where XD=2. If no rows matches that (this case happend if XD is set to an other number), so return 0 and simply hash value.
SELECT SUM(xd = 2), hash
FROM sets
WHERE id = 1
If id is a PRIMARY KEY (which I assume it is since your are using a single-record query against it), then you can just drop the SUM:
SELECT xd = 2 AS cnt, hash
FROM sets
WHERE id = 1
Update:
Sorry, got your task wrong.
Try this:
SELECT si.hash, COUNT(so.hash)
FROM sets si
LEFT JOIN
sets so
ON so.hash = si.hash
AND so.xd = 2
WHERE si.id = 1
I normally nest the statements like the following
SELECT Count(ResultA.Hash2) AS Hash2Count,
ResultA.Hash1
FROM (SELECT S.Hash AS Hash2,
(SELECT s2.hash
FROM sets AS s2
WHERE s2.ID = 1) AS Hash1
FROM sets AS S
WHERE S.XD = 2) AS ResultA
WHERE ResultA.Hash2 = ResultA.Hash1
GROUP BY ResultA.Hash1
(this one is hand typed and not tested but you should get the point)
Hash1 is your subquery, once its nested, you can reference it by its alias in the outer query. It makes the query a little larger but I don't see that as a biggy.
If I understand correctly what you are trying to get, query should look like this:
select count(case xd when 2 then 1 else null end case), hash from sets where id = 1 group by hash
I agree with the other answers, that the GROUP BY may be better, but to answer the question as posed, here's how to eliminate the repetition:
SELECT COUNT(*), h.hash
FROM sets, (SELECT hash FROM sets WHERE ID=1) h
WHERE sets.hash=h.hash
and sets.ID=1 and sets.XD=2;