Complex SQL query Issues - mysql

I have a problem selecting the data from a table. I'm sure the answer is staring me in the face, but my brain is mush. We're trying to find out which customers have bought based on only email blasts and nothing else. I can easily select any row where salesPrompt = 'email' but that might still include folks that also bought due to salesPrompt = 'postcard' or some other method. How do I select only customers that bought due the email blast? I've tried:
SELECT * FROM `customer_sales` WHERE `salesPrompt` = 'email' GROUP BY `accountID`
But that still brought up customers that had salesPrompt equaling other values.

you should check for count distint salePrompt using having and join the result
select s.*
FROM `customer_sales`
inner join (
SELECT accountID
FROM `customer_sales`
GROUP BY `accountID`
having count(distinct salesPrompt) = 1
) t on t.accountID = s.accountID
where `salesPrompt` = 'email'

Another possibility is to select all entries having the desired salesPrompt and then exclude (using EXISTS) all entries that also have further salesPrompts and the same accountid. Assuming, you want to name the main selection "target", this looks like this:
SELECT salesprompt, accountid
FROM customer_sales AS target WHERE salesprompt = 'email'
AND NOT EXISTS (SELECT 1 FROM customer_sales WHERE salesprompt != 'email'
AND accountid = target.accountid);

Related

Beginner SQL: JOIN clause skewing results of query

thank you all for taking the time to read and help if you can! I have a query below that is getting large and messy, I was hoping someone could point me in the right direction as I am still a beginner.
SELECT
DATE(s.created_time_stamp) AS Date,
s.security_profile_id AS Name,
COUNT(*) AS logins,
CASE
WHEN COUNT(s.security_profile_id) <= 1
THEN '1'
WHEN COUNT(s.security_profile_id) BETWEEN 2 AND 3
THEN '2-3'
ELSE '4+'
END AS sessions_summary
FROM session AS s
INNER JOIN member AS m
ON s.security_profile_id = m.security_profile_id
JOIN member_entitlement AS me ON m.id = me.member_id
JOIN member_package AS mp ON me.id = mp.member_entitlement_id
**JOIN member_channels AS mc ON mc.member_id = m.id**
where member_status = 'ACTIVE'
and metrix_exempt = 0
and m.created_time_stamp >= STR_TO_DATE('03/08/2022', '%m/%d/%Y')
and display_name not like 'john%doe%'
and email not like '%#aeturnum.com'
and email not like '%#trendertag.com'
and email not like '%#sargentlabs.com'
and member_email_status = 'ACTIVE'
and mp.package_id = 'ca972458-bc43-4822-a311-2d18bad2be96'
and display_name IS NOT NULL
and s.security_profile_id IS NOT NULL
**and mc.id IS NOT NULL**
GROUP BY
DATE(created_time_stamp),
Name
ORDER BY
DATE(created_time_stamp),
Name
The two parts of the query with asterisks are the two most recently added clauses and they skew the data. Without these, the query runs fine. I am trying get a session summary which works fine, but I only want the sessions of people who have a 'channel' created. Maybe mc.id IS NOT NULL is not the way to do this. I will share my query that shows me how many people have created channels. Essentially, I am trying to combine these two queries in the cleanest way possible. Any advice is greatly appreciated!
-- Users that have Topic Channels and Finished Set Up FOR TRIAL DASH**
select count(distinct(m.id)) AS created_topic_channel
from member m right join member_channels mc on mc.member_id = m.id
left join channels c on c.id = mc.channels_id
JOIN member_entitlement AS me ON m.id = me.member_id
JOIN member_package AS mp ON me.id = mp.member_entitlement_id
where title not like '# Mentions'
and member_status = 'ACTIVE'
and metrix_exempt = 0
and m.created_time_stamp >= STR_TO_DATE('03/08/2022', '%m/%d/%Y')
and display_name not like 'john%doe%'
and email not like '%#aeturnum.com'
and email not like '%#trendertag.com'
and email not like '%#sargentlabs.com'
and member_email_status = 'ACTIVE'
and display_name IS NOT NULL
and mp.package_id = 'ca972458-bc43-4822-a311-2d18bad2be96';
The metric I am trying to retrieve from the DB is how many users have created a channel and logged in at least twice. Thank you again and have a wonderful day!!
If id is the primary key of member_channels then it does not make sense to check if it is null.
If all you want is to check whether a member has a 'channel' created, then instead of the additional join to member_channels, which may cause the query to return more rows than expected, you could use EXISTS in the WHERE clause:
where member_status = 'ACTIVE'
and .......................
and EXISTS (SELECT 1 FROM member_channels AS mc WHERE mc.member_id = m.id)
I would guess your tables aren't at the same level of granularity. A member may have many sessions, and 0-many channels.
eg if member 123 has five sessions and creates three channels => 15 rows of data in this join.
To adjust for this, it's best practice to join on the same level of granularity. You could roll up sessions to the member level, channels to the member level, and then join both against members.

mysql SELECT EXISTS on multiple tables

Have tables: person,person_ip
Both tables have pid column as a primary key, in table person there is column state_id, in table person_ip there is column ip.
Want to discover if specified IP address is assigned to person with state_id is not equal to 2. But always got result 1, even if state_id is 0, 1 or 2. Always got 0 only if ip address is not listed at all. What am I doing wrong?
SELECT EXISTS (
SELECT person_ip.PID
FROM person_ip,person
WHERE person.PID=person_ip.PID
AND person.state_id NOT IN (2)
AND person_ip.ip='10.11.12.13'
)
this seems like a simple join.. unless i'm missing something
select person.*
from person
inner join person_ip
on person.pid = person_ip.pid
where person.state_id <> 2
and person_ip.ip_address = '10.0.0.1'
If you want to exclude the ip_address if it has been assigned to any user with state = 2, even if it has also been assigned to a user without state = 2, then try:
select max(i)
from (
select *
from (
select 1 as i
from dual
where not exists (
select 1
from person p
inner join person_ip pi
on p.pid = pi.pid
where p.state_id = 2
and pi.ip_address = '10.0.0.1'
)
) q
union
select 0
) qq
(dual is a system table that can be used as a sort of stub table)
here's a fiddle showing both versions
update after some actual sleep
Okay, so the above query is a little.. out there. Back in the real world, this one is probably more appropriate:
select count(case when p1.state_id = 2 then 1 end)
from person p1
inner join person_ip pi1
on p1.pid = pi1.pid
where pi1.ip_address = '10.0.0.1'
group by pi1.ip_address;
This will return 1 or more if your ip_address has been used by someone with a state_id of 2, and 0 if it has never been used by someone with a state_id of 2.
It will return nothing if the ip has never been used.
this fiddle has all three of the above queries.
SELECT IF(COUNT(*)>0,1,0)
FROM person
INNER JOIN person_ip
ON person.pid = person_ip.pid
AND person_ip.ip_address = '10.0.0.1'
WHERE person.state_id <> 2

MySQL Database design advice - using joins

I am building an AJAX like search page which allows a customer to select a number filters that will narrow down the search. For instance, a user has selected an 'iPhone 5' and has additional filters for capacity (32GB, 64GB) & colour (black, white..).
The user can only select a single radio box per category (so they could select 32GB & Black).. but they could not select (32GB & 64GB & black as two of these belong to the 'capacity' category).
I have added the schema here on sqlfiddle (please ignore the fact i've removed the primary keys they exist in the proper app they have just been removed along with some other fields/data to minimise the sqlfiddle)
http://sqlfiddle.com/#!2/964425
Can anyone suggest the best way to create the query to do the following:
Get all the prices for device_id '2939' (iPhone 5) which has the 'attributes' of '32GB' AND 'Black'
I currently have this - but this only works when selecting for a single attribute:
// search for device with '64GB' & 'Black' attributes (this currently doesn't return any rows)
SELECT `prices`.*
FROM (`prices`)
LEFT JOIN `prices_attributes` ON `prices_attributes`.`price_id` = `prices`.`id`
WHERE `prices`.`device_id` = '2939'
AND `attribute_option_id` = '19'
AND `attribute_option_id` = '47';
// search for device with '64GB' attribute only (this currently DOES return a row)
SELECT `prices`.*
FROM (`prices`)
LEFT JOIN `prices_attributes` ON `prices_attributes`.`price_id` = `prices`.`id`
WHERE `prices`.`device_id` = '2939'
AND `attribute_option_id` = '19';
Any advice on the database design would be appreciated too
Note: I was thinking to have a new column within the 'prices' table that has the matching attribute_ids serialised - would this be not good for optimisation however (e.g would it be slower than the current method)
Since attribute_option_id is an atomic value, it cannot have two different values for the same row. So your WHERE clause cannot match any record:
SELECT `prices`.*
FROM (`prices`)
LEFT JOIN `prices_attributes` ON `prices_attributes`.`price_id` = `prices`.`id`
WHERE `prices`.`device_id` = '2939'
AND `attribute_option_id` = '19' # Here for one row, attribute_option_id is either 19
AND `attribute_option_id` = '47'; # of '47'. Cannot be the both
Instead of JOIN, you could try a subquery if you feel that is more readable. I think MySQL allow that syntax:
SELECT `prices`.*
FROM `prices`
WHERE `prices`.`device_id` = '2939'
AND EXISTS (SELECT *
FROM prices_attributes
WHERE price_id = `prices`.`id`
AND attribute_option_id IN ('19', '47') )
I don't know how MySQL will optimize the above solution. An alternative would be:
SELECT `prices`.*
FROM `prices`
WHERE `prices`.`id` IN (
SELECT DISTINCT `price_id`
FROM prices_attributes
WHERE attribute_option_id IN ('19', '47')
)
I think you should use the IN operator for the attribute_option_id and you set the values dynamically to the query; Also, using group_by you have only one row per price so in effect you get all the prices. Apart from this, the design is ok.
Here, I have made an example:
SELECT `prices`.*
FROM (`prices`)
LEFT JOIN `prices_attributes` ON `prices_attributes`.`price_id` = `prices`.`id`
WHERE `prices`.`device_id` = '2939'
and `attribute_option_id` in ('19','47')
group by `prices`.`device_id`, `prices`.`price`;
Here, you can also add an order clause to order by price:
order by `prices`.`price` desc;
Another way to solve this would be to use a distinct on price, like this:
select distinct(prices.price)
from prices
where prices.device_id = 2939
and id in (select price_id from prices_attributes where attribute_option_id in (19,47));
Join against the devices_attributes_options table several times, once for each attribute the item must have
Something like this:-
SELECT *
FROM devices a
INNER JOIN prices b ON a.id = b.device_id
INNER JOIN prices_attributes c ON b.id = c.price_id
INNER JOIN devices_attributes_options d ON c.attribute_option_id = d.id AND d.attribute_value = '32GB'
INNER JOIN devices_attributes_options e ON c.attribute_option_id = e.id AND e.attribute_value = 'Black'
WHERE a.id = 2939
As to putting serialised details into a field, this is a really bad idea and would come back to bite you in the future!
SELECT * FROM prices WHERE device_id=2939 AND id IN (SELECT price_id FROM prices_attributes WHERE attribute_option_id IN (19,47));
Is it what you're looking for?
EDIT: sorry, didn't notice you're asking for query using joins

MySQL Complicated Contacts Table

I am trying to output a list of contact names with their phone number and email address for a given company.
The problem I am facing is getting it to output a contact based on the following criteria:
Contacts may or may not have a name, email or telephone, but they must have at least one of these to appear in the results.
There can be more than one contact per company.
There can be more than one email address and/or telephone number per contact.
There is a primary flag on contacts, so if there is more than one contact and one of them is primary, it should pick that one instead of the other non-primary one.
I have tried the following for getting the contacts name but with no success:
SELECT entity_details.name,
COALESCE(
(SELECT entity_contacts.name FROM entity_contacts
WHERE entity_contacts.entityRef = entity_details.id
ORDER BY entity_contacts.isPrimary = 1),
(SELECT entity_contacts.name FROM entity_contacts
WHERE entity_contacts.entityRef = entity_details.id)
)
AS contact
FROM entity_details
WHERE entity_details.ownerRef = ?
This is the closest thing I can get to but I am unsure of if it's correct or not, and it doesn't prioritise primary contacts, it just selects any and groups on the entityRef to remove duplicates:
SELECT
entity_details.name, entity_contacts.name AS contact,
entity_contacts_telephones.tel, entity_contacts_emails.email
FROM entity_details
LEFT JOIN entity_contacts ON entity_details.id = entity_contacts.entityRef
LEFT JOIN entity_contacts_telephones ON entity_contacts.id = entity_contacts_telephones.contactRef
LEFT JOIN entity_contacts_emails ON entity_contacts.id = entity_contacts_emails.contactRef
WHERE entity_details.ownerRef = ?
GROUP BY entity_contacts.entityRef
LIMIT ?, ?
All tables are Innobd, the ones I am working with are in the above edit. All references etc have indexes on where nesisary.
In entity_details there around about 13000 rows, 12000 in entity_contacts, and a few 1000 in entity_contacts_telephones and entity_contacts_emails.
I thought the following would work but it doesn't:
LEFT JOIN entity_contacts_telephones
ON entity_contacts.id = entity_contacts_telephones.contactRef
AND COALESCE(entity_contacts_telephones.isPrimary = 1, 0)
This may work (not sure mainly because it's not clear how many rows per entity you can have in each table):
SELECT
entity_details.name,
( SELECT entity_contacts.name
FROM entity_contacts
WHERE entity_contacts.entityRef = entity_details.id
ORDER BY entity_contacts.isPrimary DESC
LIMIT 1
) AS contact
FROM entity_details
WHERE entity_details.ownerRef = ?
You probably need a join - of the [greatest-n-per-group] type:
SELECT
d.name,
...
c.whatever
...
FROM
entity_details AS d
JOIN
entity_contacts AS c
ON c.PK = --- the PRIMARY KEY of contacts table
( SELECT cc.PK
FROM entity_contacts AS cc
WHERE cc.entityRef = d.id
ORDER BY cc.isPrimary DESC
LIMIT 1
)
WHERE d.ownerRef = ?
An index on (entityRef, isPrimary) would help improving peformance.

How to add check against data within a MySQL query?

I have three tables:
$sTable = a table of songs (songid, mp3link, artwork, useruploadid etc.)
$sTable2 = a table of projects with songs linked to them (projectid, songid, project name etc.)
$sTable3 = a table of song ratings (songid, userid, rating)
All this data is output to a JSON array and displayed in a table in my application to provide a list of songs, combined with the projects and ratings data.
What I want to be able to do is check to see if the "logged in user" has voted on a particular song so that I can add a class of 'voted' to the parent element of the returned data.
I would lke to do this in the most permance optimal way which I would guess would be to return a boolean value (1 or 0) with 1 being voted and 0 being returned otherwise.
I can then use javascript to apply the class client side.
The 'logged in user id' is stored in my PHP script as $loggedin_ID so I need to simply check this variable against the column 'userid' of $sTable3 for a given songid and return a new column (I would imagine using AS) with a result of 1 if there is a matching entry for that songid and 0 if there is not.
How would I go about modifying my query to add this?
The above are just my thoughts and there may indeed be a far better/more effecient method. If so please do not hesitate to provide what you think might be a better solution to achieving this functionality.
Below is my current query. Thanks.
$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable b
LEFT JOIN (
SELECT COUNT(*) AS projects_count, a.songs_id
FROM $sTable2 a
GROUP BY a.songs_id
) bb ON bb.songs_id = b.songsID
LEFT JOIN (
SELECT AVG(rating) AS rating, COUNT(rating) AS ratings_count,c.songid
FROM $sTable3 c
GROUP BY c.songid
) bbb ON bbb.songid = b.songsID
May be you are looking for something like this:
select s.songid, s.userid,
case when exists
(
select songid
from sTable3
where songid = $songid
) Then 'Voted'
else
(
'Not Voted'
)
end
as 'Voted or Not'
from sTable3 s
where s.userid = $userid