SQL conditional join challenge - mysql

I have 2 tables stores and shares in a mysql database. I am trying to avoid an IN clause. Please see below for more details
select id, user_id from stores where user_id =7;
+----+---------+
| id | user_id |
+----+---------+
| 36 | 7 |
| 37 | 7 |
select stores_id,share_id from shares where share_id=7;
+-----------+----------+
| stores_id | share_id |
+-----------+----------+
| 15 | 7 |
| 38 | 7 |
Now I run this
SELECT stores.id
FROM stores
WHERE user_id = 7
UNION
(SELECT stores.id
FROM stores
WHERE id IN (SELECT stores_id
FROM shares
WHERE share_id = 7));
To get the below result:
+----+
| id |
+----+
| 36 |
| 37 |
| 15 |
| 38 |
+----+
QUESTION
How can I rewrite the query so that I don't use the IN key word.?

You can use either EXISTS:
WHERE EXISTS
( SELECT 1
FROM shares
WHERE share_id = 7
AND stores_id = stores.id
)
or JOIN:
JOIN shares
ON shares.stores_id = stores.id
AND shares.share_id = 7
(Note that the JOIN potentially returns multiple copies of some stores, but because UNION implies SELECT DISTINCT, that won't actually affect your final result-set.)

This can help to you:
select stores.id from stores where user_id = 7
UNION
select s1.id from stores s1
inner join shares s2
on s2.share_id = 7
and s1.id = s2.stores_id;

If all you need is the ID, this will do just fine...
SELECT stores.id
FROM stores
WHERE user_id = 7
UNION
SELECT stores_id as id
FROM shares
WHERE share_id = 7
But if you need some data from the other columns in the stores table, INNER JOIN or EXISTS will be your best bet.

A left join should accomplish what you are looking for:
select distinct stores.id
from stores
left join shares on stores.id = shares.stores_id
where stores.user_id = 7
or shares.share_id = 7

Related

How to count in mysql

I have this query in mySQL where I would like to sum the line product of each doctor but I dont know how to do it.
use avant_medical;
select
sales.doctor_id as DoctorID,
line_products.id as LineProductID,
line_products.name as LineProductName
from `doctors`
inner join `sales` on `doctors`.`id` = `sales`.`doctor_id`
inner join `inventories` on `sales`.`id` = `inventories`.`sale_id`
inner join `products` on `inventories`.`product_id` = `products`.`id`
inner join `line_products` on `products`.`lineProduct_id` = `line_products`.`id`
order by `doctors`.`id` asc;
lPID= lineProductID
|DrID|lPID |
| -- | ----|
| 1 | 7 |
| 1 | 6 |
| 1 | 6 |
| 1 | 7 |
| 1 | 7 |
| 1 | 7 |
| 1 | 6 |
This is how I want:
Doctor 1
lineID | quantity
7 | 4
6 | 3
I try this query only in mySQL
The keyword you are looking for is count, not sum. Summing would add up every lineProductID as if they where regular mathematical values, while counting will add up how many times a given lineProductID is found.
select
sales.doctor_id as DoctorID,
line_products.id as LineProductID,
line_products.name as LineProductName,
-- We count the number of occurrences of each line_product.id
COUNT(line_products.id) as LineProductQty
from `doctors`
inner join `sales` on `doctors`.`id` = `sales`.`doctor_id`
inner join `inventories` on `sales`.`id` = `inventories`.`sale_id`
inner join `products` on `inventories`.`product_id` = `products`.`id`
inner join `line_products` on `products`.`lineProduct_id` = `line_products`.`id`
-- Never forget to properly GROUP your aggregate functions, such as COUNT() or SUM()!
GROUP BY sales.doctor_id, line_products.id, line_products.name
order by `doctors`.`id` asc;
Since you didn't provided full schema to test this, I made a small, very artificial demo, but should be representative of how the query above works.

SQL select from 1 x N where all bigger than

I have tables books and bookType which pose a 1 X n relationship.
books
+-----+------------------+----------+-------+
| id | title | bookType | price |
+-----+------------------+----------+-------+
| 1 | Wizard of Oz | 3 | 14 |
| 2 | Huckleberry Finn | 1 | 16 |
| 3 | Harry Potter | 2 | 25 |
| 4 | Moby Dick | 2 | 11 |
+-----+------------------+----------+-------+
bookTypes
+-----+----------+
| id | name |
+-----+----------+
| 1 | Fiction |
| 2 | Drama |
| 3 | Children |
+-----+----------+
How would I retrieve bookTypes where all books are more expensive than e.g. 12($)?
In this case, the expected output would be:
+-----+----------+
| id | name |
+-----+----------+
| 1 | Fiction |
| 3 | Children |
+-----+----------+
You can use not exists:
select t.*
from bookTypes t
where not exists (
select 1
from books b
where b.bookType = t.id and b.price < 12
)
If you want to select book types that also have at least one associated book:
select t.*
from bookTypes t
where
exists (select 1 from books b where b.bookType = t.id)
and not exists (select 1 from books b where b.bookType = t.id and b.price < 12)
Do a GROUP BY, use HAVING to return only booktypes having the lowest price > 12.
SELECT bt.name
FROM bookTypes bt
INNER JOIN books b ON b.bookType = bt.id
group by bt.name
HAVING SUM(b.price <= 12) = 0;
You can directly consider using having min(price) >= 12 with grouping by bookType
select t.id, t.name
from bookTypes t
join books b
on t.id = b.bookType
group by b.bookType
having min(price) >= 12
Moreover, if your DB's version is at least 10.2, then you can also use some window functions for analytical queries such as min(..) over (partition by .. order by ..) :
with t as
(
select t.id, t.name, min(price) over (partition by bookType) as price
from bookTypes t
join books b
on t.id = b.bookType
)
select id, name
from t
where price >= 12
in which min() over (..) window function determines minimum price for each booktype by use of partition by bookType
Demo
I think GMB's solution is likely the best so far. But for sake of completeness: You can also use the ALL operator with a correlated subquery. That's probably the most straight forward solution.
SELECT *
FROM booktypes bt
WHERE 12 < ALL (SELECT b.price
FROM books b
WHERE b.booktype = bt.id);
Can you not just select from books inner join bookTypes on id WHERE price > 12?
SELECT bt.*
FROM bookTypes bt
INNER JOIN books b ON b.bookType = bt.id
WHERE b.price > 12

Prefix best match MySQL

That's my scenario.
I have 4 tables: records, providers, routing_domain, domains.
domains: id, name (something like 'example.com')
providers: id, name (something like 'TLC')
records: phone_number (varchar), provider_id (foreign key to
providers)
routing_domain: provider_id (foreign key to providers), domain_id
(foreign key to domains) and prefix (varchar).
Example of tables:
mysql> select id,name from domains;
+----+-----------------------+
| id | name |
+----+-----------------------+
| 1 | e164.arpa |
| 3 | example.com |
| 0 | localhost.localdomain |
| 4 | luigi.it |
| 2 | tim.it |
+----+-----------------------+
mysql> select id,name from providers where id in (9,10);
+----+----------+
| id | name |
+----+----------+
| 9 | TIM |
| 10 | VODAFONE |
+----+----------+
mysql> select * from routing_domain;
+----+--------+-----------+-------------+
| id | prefix | domain_id | provider_id |
+----+--------+-----------+-------------+
| 3 | 3932 | 4 | 9 |
| 1 | 39320 | 2 | 9 |
| 2 | 39321 | 3 | 10 |
+----+--------+-----------+-------------+
Now,
given a phone_number '39320xxxxxxx' with provider_id 9, i need to get
domain_id=2;
given a phone_number '39321xxxxxxx' with provider_id 9, i need to get
domain_id=4;
So, given a certain phone_number '3932xxxxxxxx' with provider_id=9, i need to do some bestmatch searching. Starting to search prefix with 6 chars, if not match, try with 5 chars and so on, until 3 chars (393).
I managed to get the correct domain from phone_number searching only from a prefix to 5 chars.
Something like:
select * FROM records r
left join routing_domain rd on rd.prefix like SUBSTRING(r.phone_number,1,5) and r.provider_id = rd.provider_id
left join providers p on p.id = rd.provider_id
left join domains d on d.id = rd.domain_id
where r.name = 'xxxxxxxxxxxx';
Any advices to do this bestmatch ?
Thank you so much!
Update
I tried with this:
select * FROM records r
left join routing_domain rd on on r.phone_number like concat(rd.prefix, '%') and r.provider_id = rd.provider_id
left join providers p on p.id = rd.provider_id
left join domains d on d.id = rd.domain_id
where r.name = 'xxxxxxxxxxxx';
Now, if i search for '39325xxxxxxx', there is a match with prefix '3932',
but if i search for '39320xxxxxxx', both prefixes will match and the search returns 2 rows.
One option is to have a sub-query that gives you the longest prefix matching provider_id and prefix. Something like this:
select domain_id from routing_domain
where
provider_id = 9
and '39321xxxxxxx' like concat(prefix, '%')
and length(prefix) =
( select max(length(prefix))
from routing_domain
where
provider_id = 9
and '39321xxxxxxx' like concat(prefix, '%')
)
See my fiddle here.
http://sqlfiddle.com/#!9/2e36df/10
SELECT r.*,
MAX(IF(rd.prefix = LEFT(r.phone_number,5),rd.prefix,
IF(rd.prefix = LEFT(r.phone_number,4),rd.prefix,
IF(rd.prefix = LEFT(r.phone_number,3),rd.prefix,''))))
FROM records r
LEFT JOIN routing_domain rd
ON r.provider_id = rd.provider_id
GROUP BY r.id
And to make it closer to your attempt:
http://sqlfiddle.com/#!9/2e36df/17
SELECT t.*, p.*, d.*
FROM (
SELECT r.*,
MAX(IF(rd.prefix = LEFT(r.phone_number,5),rd.id,
IF(rd.prefix = LEFT(r.phone_number,4),rd.id,
IF(rd.prefix = LEFT(r.phone_number,3),rd.id,'')))) as rd_id
FROM records r
LEFT JOIN routing_domain rd
ON r.provider_id = rd.provider_id
#WHERE r.phone_number = '393xxxxxxxxxx'
GROUP BY r.id
) t
LEFT JOIN routing_domain rd
ON t.rd_id = rd.id
LEFT JOIN providers p
ON p.id = rd.provider_id
LEFT JOIN domains d
ON d.id = rd.domain_id

Multi join one to many

Trades
id |Trade_name |
1 | trade1 |
2 | trade2 |
3 | trade3 |
4 | trade4 |
Users
Name | Primary_id(FK to trade.id) | secondary_id (FK to trade.id) |
John | 1 | 2 |
Alex | 3 | 4 |
This is my current SQL which joins trades.t1 to primary & secondary.id:
select
`users`.`name` ,
`t1`.`trade_name` AS `Primary_trade`,
`t2`.`trade_name` AS `Secondary_trade`,
FROM `users`
right JOIN `trades` `t1` On (`t1`.`trade_id` = `users`.`primary_trade_id`)
right JOIN `trades` `t2` on (`t2`.`trade_id` = `users`.`secondary_trade_id`)
My question is, how do I identify which trades are not used for users both as primary or secondary. I want to see record where a trade does not exist in both primary or secondary column so I can perform housekeeping.
Thanking you all in advance for your help.
If you need only the trades rows
SELECT t.*
FROM trades t
WHERE NOT EXISTS ( SELECT 'u'
FROM Users u
WHERE u.Primary_id = t.id
OR u.Secondary_id = t.id
)
I think this should work for you:
SELECT * FROM trades WHERE id NOT IN (SELECT Primary_id FROM Users) AND id NOT IN (SELECT Secondary_id FROM Users)
It selects the rows which are not in either primary_id nor secondary_id

Finding the MIN value that appears for each unique value in either of two other columns

Given the following (simplified) tables:
People p
id name registered
-----------------------------------
1 Geoff 2011-03-29 12:09:08
2 Phil 2011-04-29 09:03:54
3 Tony 2011-05-29 21:22:23
4 Gary 2011-06-21 22:56:08
...
Items i
date p1id p2id
----------------------------------------
2011-06-29 20:09:44 1 2
2011-06-26 10:45:00 1 3
2011-06-23 12:22:43 2 3
2011-06-22 13:07:12 2 4
...
I'd like:
The earliest single i.date that each p.id appears in either column p1id or p2id; or p.registered if they feature in neither.
So far, I've tried:
CREATE TEMPORARY TABLE temp (id INT);
INSERT INTO temp (id)
SELECT DISTINCT u FROM (
SELECT p1id AS u FROM Items UNION ALL
SELECT p2id AS u FROM Items
)tt;
SELECT registered,id FROM People
WHERE id NOT IN (SELECT id FROM temp);
Which gets me as far as the second part, albeit in a fairly clumsy way; and I'm stuck on the first part beyond some sort of external, scripted iteration through all the values of p.id (ugh).
Can anyone help?
I'm on MySQL 5.1 and there's ~20k people and ~100k items.
One more solution:
SELECT id, name, IF(min_date1 IS NULL AND min_date2 IS NULL, registered, LEAST(COALESCE(min_date1, min_date2), COALESCE(min_date2, min_date1))) date FROM (
SELECT p.id, p.name, p.registered, MIN(i1.date) min_date1, MIN(i2.date) min_date2 FROM people p
LEFT JOIN items i1
ON p.id = i1.p1id
LEFT JOIN items i2
ON p.id = i2.p2id
GROUP BY id
) t;
OR this:
SELECT p.id, p.name, COALESCE(MIN(i.date), p.registered) FROM people p
LEFT JOIN (
SELECT p1id id, date FROM items
UNION ALL
SELECT p2id id, date FROM items
) i
ON p.id = i.id
GROUP BY id;
Result:
+------+-------+---------------------+
| id | name | date |
+------+-------+---------------------+
| 1 | Geoff | 2011-06-26 10:45:00 |
| 2 | Phil | 2011-06-22 13:07:12 |
| 3 | Tony | 2011-06-23 12:22:43 |
| 4 | Gary | 2011-06-22 13:07:12 |
+------+-------+---------------------+
This is tested in Postgres, but I think it ought to work in MySQL with few or no changes:
SELECT p.id,COALESCE(MIN(x.date),p.registered) AS date
FROM p
JOIN (
SELECT p.id,MIN(i.date) AS date
FROM p
JOIN i ON (p.id=i.p1id)
GROUP BY p.id
UNION
SELECT p.id,MIN(i.date) AS date
FROM p
JOIN i ON (p.id=i.p2id)
GROUP BY p.id
) AS x ON x.id = p.id
GROUP BY p.id,p.registered;
Output (given your sample data):
id | date
----+---------------------
3 | 2011-06-23 12:22:43
1 | 2011-06-26 10:45:00
2 | 2011-06-22 13:07:12
4 | 2011-06-22 13:07:12
(4 rows)