Doctrine query subset of one-to-many relation - sql

I ve the following tables:
mysql> show columns from Person;
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
|guid | varchar(255) | NO | PRI | NULL | |
+------------+--------------+------+-----+---------+-------+
mysql> show columns from Person_Func;
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| Person_id | varchar(255) | NO | PRI | NULL | |
| Func_id | varchar(255) | NO | PRI | NULL | |
+-----------+--------------+------+-----+---------+-------+
mysql> show columns from Func;
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| entry | varchar(255) | NO | | NULL | |
| description | varchar(255) | NO | | NULL | |
| Guid | varchar(255) | NO | PRI | NULL | |
+-------------+--------------+------+-----+---------+-------+
Symfony class Person contains one-to-many relation to Func (one Person - several Funcs) using join table Person_Func. I want to query for Person, who has got a number of Funcs -
steve (a, b , c); john (a, b, d); ele (b, d) - and I query for (a, b) functions and steve and john should be returned.
Right now I am just iterating thru all the persons and querying for Functions - that's very-very slow. Could you please help me?
UPD
I have succeeded with
SELECT DISTINCT d1.guid from (select p.guid, f.entry from Person p, Person_Func jt, Func f where p.Guid = jt.person_id and jt.func_id = f.guid and f.entry in ('A', 'B')) as d1,
(select p.guid, f.entry from Person p, Person_Func jt, Func f where p.Guid = jt.person_id and jt.func_id = f.guid and f.entry in ('A', 'B')) as d2
where d1.guid=d2.guid and d1.entry != d2.entry
But I think that that's a not a good idea, yes?

Linking Person and Person_Func with JOIN is a cleaner way of doing it:
SELECT p.id
FROM Person p INNER JOIN Person_Func pf ON p.id = pf.person_id
INNER JOIN Person_Func pf2 ON p.id = pf2.person_id
WHERE
pf.func_id = 'a'
AND pf2.func_id = 'b'
Here you have the SQLFiddle code

Related

How to join a polymorphic table with its child tables?

I am sorry about not being able to articulate the title of the question or the description of this question better. However, I will give the schema, sample data and expected result. Please help me write a query for such a use case.
Schema of restaurants
id
name
item_type
item_id
Schema of foods
id
name
Schema of food_items
id
name
food_id
Sample data in restaurants
|---------------------|------------------|---------------------|------------------|
| id | name | item_type | item_id |
|---------------------|------------------|---------------------|------------------|
| 1 | Apple Crushers | food_items | 1 |
|---------------------|------------------|---------------------|------------------|
| 2 | Retro Cafe | foods | 2 |
|---------------------|------------------|---------------------|------------------|
| 3 | Fruit Mania | foods | 1 |
|---------------------|------------------|---------------------|------------------|
| 4 | Meat and Eat | NULL | NULL |
|---------------------|------------------|---------------------|------------------|
Sample data in foods:
|---------------------|------------------|
| id | Name |
|---------------------|------------------|
| 1 | Fruits |
|---------------------|------------------|
| 2 | Chocolates |
|---------------------|------------------|
Sample data in food_items
|---------------------|------------------|---------------------|
| id | Name | food_id |
|---------------------|------------------|---------------------|
| 1 | Apple | 1 |
|---------------------|------------------|---------------------|
| 2 | Mango | 1 |
|---------------------|------------------|---------------------|
I need to write a query such that I get this as my result.
|---------------------|------------------|---------------------|------------------|---------------------|------------------|
| r_id | r_name | food_id | food_name | food_item_id | food_item_name |
|---------------------|------------------|---------------------|------------------|---------------------|------------------|
| 1 | Apple Crushers | 1 | Fruit | 1 | Apple |
|---------------------|------------------|---------------------|------------------|---------------------|------------------|
| 2 | Retro Cafe | 2 | Chocolates | NULL | NULL |
|---------------------|------------------|---------------------|------------------|---------------------|------------------|
| 3 | Fruit Mania | 1 | Fruit | NULL | NULL |
|---------------------|------------------|---------------------|------------------|---------------------|------------------|
| 4 | Meat and Eat | NULL | NULL | NULL | NULL |
|---------------------|------------------|---------------------|------------------|---------------------|------------------|
p.s: It will also be very helpful if someone could come up with an appropriate title and description for this problem. I am lost for words to describe this.
You must join the food table twice and use COALESCE:
select
r.id,
r.name,
coalesce(f.id, fif.id) as food_id,
coalesce(f.name, fif.name) as food_name,
fi.id as food_item_id,
fi.name as food_item_name
from restaurants r
left join foods f on f.id = r.item_id and r.item_type = 'foods'
left join food_items fi on fi.id = r.item_id and r.item_type = 'food_items'
left join foods fif on fif.id = fi.food_id
order by r.id;
select r.id, r.name, foods.id, foods.name, food_items.id, food_items.name from restaurents as r
left join food_items on r.item_type = 'food_items' and r.item_id = food_items.id
left join foods on (r.item_type = 'foods' and r.item_id = foods.id) or (r.item_type = 'foods' and r.item_id = food_items.food_id)
This might be having some syntax issues related to table names, but it should work.
For your database, I would suggest another data model based on compound keys. This would guarantee data consistency and makes queries a tad simpler:
food_group
(
food_group_no integer not null,
name varchar(100) not null,
primary key (food_group_no)
);
food
(
food_group_no integer not null,
food_no integer not null,
name varchar(100) not null,
primary key (food_group_no, food_no)
);
restaurant
(
restaurant_no integer not null,
name varchar(100) not null,
food_group_no integer not null,
food_no integer null,
primary key (restaurant_id),
foreign key (food_group_no) references food_group(food_group_no),
foreign key (food_group_no, food_no) references food(food_group_no, food_no)
);
The query:
select
r.restaurant_no,
r.name as restaurant_name,
fg.food_group_no,
fg.name as food_group_name,
f.food_id,
f.name as food_name
from restaurants r
join food_group fg on fg.id = r.food_group_no
left join food f on f.food_group_no = r.food_group_no and f.food_no = r.food_no
order by r.id;

Get column value if it matches another column value in the same table

I have a SQLite table with comments like:
Id | replyId | commentID_parentID | usernameChannelId | channelId
1 | NULL | NULL | a | g
2 | NULL | NULL | b | k
NULL | 1.k | 1 | a | p
NULL | 1.p | 1 | c | i
3 | NULL | NULL | d | h
NULL | 2.k | 2 | g | g
and a table with channels like:
I want to know which user (userChannelId) replied to which user.
So I take a row with a comment and check if:
Id == NULL? Then it's a reply -> get userChannelId where commentID_parentID == Id
Id != NULL? Then it's a main comment -> userChannelId replied to channelId
And result should be:
userChannelId_Source | userChannelId_Target
a | g
b | k
a | a
c | a
g | b
Comment "d" has no entry where commentID_parentID == Id so it's left out.
How can I do that in SQL when I query in the same table?
It's a rather complicated requirement but I think that a conditional self join will do it:
select t.usernameChannelId userChannelId_Source,
case
when t.id is not null then tt.channelId
else tt.usernameChannelId
end userChannelId_Target
from tablename t inner join tablename tt
on tt.id = coalesce(t.id, t.commentID_parentID)
and exists (
select 1 from tablename
where commentID_parentID = t.id
or (commentID_parentID is null and t.id is null)
)
See the demo.
Results:
| userChannelId_Source | userChannelId_Target |
| -------------------- | -------------------- |
| a | g |
| a | a |
| c | a |
| b | k |
| g | b |

Sub-query producing an empty set

I am trying to provide a list of active quarterbacks who play for teams who had 20 or more sacks during the season.
I have information in two tables, one of them is a view(v_active_quarterbacks) which shows which quarterbacks are active, the other is the table team_game_stats.
I created the command that lists the teams that have 20+ sacks.
SELECT SUM(sacks)
FROM team_game_stats
GROUP BY team_code
HAVING SUM(sacks) > 20;
I now need to connect this to v_active_quarterbacks so that I can get a list. I have tried the following but it just provides an empty set.
SELECT player_code
FROM v_active_quaterbacks
INNER JOIN team_game_stats ON v_active_quaterbacks.team_code = team_game_stats.team_code
WHERE sacks IN (SELECT SUM(sacks)
FROM team_game_stats
GROUP BY team_code
HAVING SUM(sacks) > 20);
Here is the view description:
+-----------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+-------------+------+-----+---------+-------+
| player_code | int(11) | NO | | NULL | |
| first_name | varchar(30) | YES | | NULL | |
| last_name | varchar(30) | YES | | NULL | |
| team_code | int(11) | YES | | NULL | |
| uniform_number | varchar(3) | YES | | NULL | |
| passes_player_code | int(11) | YES | | NULL | |
| COUNT(passes.attempt) | bigint(21) | NO | | 0 | |
+-----------------------+-------------+------+-----+---------+-------+
At this point I am confused and stuck. Any help would be appreciated.
You could use a an inner join on subselect for team_code and sum
SELECT player_code , T.sum_sacks
FROM v_active_quaterbacks
INNER JOIN team_game_stats ON v_active_quaterbacks.team_code = team_game_stats.team_code
INNER JOIN (
SELECT team_code, SUM(sacks) sum_sacks
FROM team_game_stats
GROUP BY team_code
HAVING SUM(sacks) > 20
) T on T.team_code = v_active_quaterbacks.team_code

4 table query / join. getting duplicate rows

So I have written a query that will grab an order (this is for an ecommerce type site), and from that order id it will get all order items (ecom_order_items), print options (c_print_options) and images (images). The eoi_p_id is currently a foreign key from the images table.
This works fine and the query is:
SELECT
eoi_parentid, eoi_p_id, eoi_po_id, eoi_quantity,
i_id, i_parentid,
po_name, po_price
FROM ecom_order_items, images, c_print_options WHERE eoi_parentid = '1' AND i_id = eoi_p_id AND po_id = eoi_po_id;
The above would grab all the stuff I need for order #1
Now to complicate things I added an extra table (ecom_products), which needs to act in a similar way to the images table. The eoi_p_id can also point at a foreign key in this table too. I have added an extra field 'eoi_type' which will either have the value 'image', or 'product'.
Now items in the order could be made up of a mix of items from images or ecom_products. Whatever I try it either ends up with too many records, wont actually output any with eoi_type = 'product', and just generally wont work. Any ideas on how to achieve what I am after? Can provide SQL samples if needed?
SELECT
eoi_id, eoi_parentid, eoi_p_id, eoi_po_id, eoi_po_id_2, eoi_quantity, eoi_type,
i_id, i_parentid,
po_name, po_price, po_id,
ep_id
FROM ecom_order_items, images, c_print_options, ecom_products WHERE eoi_parentid = '9' AND i_id = eoi_p_id AND po_id = eoi_po_id
The above outputs duplicate rows and doesnt work as expected. Am I going about this the wrong way? Should I have seperate foreign key fields for the eoi_p_id depending it its an image or a product?
Should I be using JOINs?
Here is a mysql explain of the tables in question
ecom_products
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| ep_id | int(8) | NO | PRI | NULL | auto_increment |
| ep_title | varchar(255) | NO | | NULL | |
| ep_link | text | NO | | NULL | |
| ep_desc | text | NO | | NULL | |
| ep_imgdrop | text | NO | | NULL | |
| ep_price | decimal(6,2) | NO | | NULL | |
| ep_category | varchar(255) | NO | | NULL | |
| ep_hide | tinyint(1) | NO | | 0 | |
| ep_featured | tinyint(1) | NO | | 0 | |
+-------------+--------------+------+-----+---------+----------------+
ecom_order_items
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| eoi_id | int(8) | NO | PRI | NULL | auto_increment |
| eoi_parentid | int(8) | NO | | NULL | |
| eoi_type | varchar(32) | NO | | NULL | |
| eoi_p_id | int(8) | NO | | NULL | |
| eoi_po_id | int(8) | NO | | NULL | |
| eoi_quantity | int(4) | NO | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
c_print_options
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| po_id | int(8) | NO | PRI | NULL | auto_increment |
| po_name | varchar(255) | NO | | NULL | |
| po_price | decimal(6,2) | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
images
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| i_id | int(8) | NO | PRI | NULL | auto_increment |
| i_filename | varchar(255) | NO | | NULL | |
| i_data | longtext | NO | | NULL | |
| i_parentid | int(8) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
You're missing a join condition for ecom_products either in the WHERE or FROM Clause. This is how it would be done using ANSI-92 joins
SELECT
eoi_id,
eoi_parentid,
eoi_p_id,
eoi_po_id,
eoi_po_id_2,
eoi_quantity,
eoi_type,
i_id,
i_parentid,
po_name,
po_price,
po_id,
ep_id
FROM
ecom_order_items,
LEFT JOIN images
ON i_id = eoi_p_id
LEFT JOIN c_print_options
ON po_id = eoi_po_id
INNER JOIN ecom_products
ON eoi_p_id = ep_id
WHERE
eoi_parentid = '9'
ANSI 92 joins are preferred and its a little clearer what's a join and what's filtering. That said you could just add AND eoi_p_id = ep_id to you where clause.
This is how I'd write the first query. I prefer to use joins.
SELECT eoi_parentid, eoi_p_id, eoi_po_id, eoi_quantity, i_id, i_parentid, po_name, po_price
FROM ecom_order_items
INNER JOIN images
ON i_id = eoi_p_id
INNER JOIN c_print_options
ON po_id = eoi_po_id
WHERE eoi_parentid = '1'
For your second query I would use a UNION on two queries, one for images and one for products.
SELECT eoi_id, eoi_parentid, eoi_p_id, eoi_po_id, eoi_po_id_2, eoi_quantity, eoi_type, i_id, i_parentid, po_name, po_price, po_id, ep_id
FROM ecom_order_items
INNER JOIN images
ON i_id = eoi_p_id
INNER JOIN c_print_options
ON po_id = eoi_po_id
WHERE eoi_type = 'image' AND i_id = eoi_p_id --Image conditions
AND eoi_parentid = '9'
AND po_id = eoi_po_id
UNION
SELECT eoi_id, eoi_parentid, eoi_p_id, eoi_po_id, eoi_po_id_2, eoi_quantity, eoi_type, i_id, i_parentid, po_name, po_price, po_id, ep_id
FROM ecom_order_items
INNER JOIN images
ON i_id = eoi_p_id
INNER JOIN c_print_options
ON po_id = eoi_po_id
WHERE eoi_type = 'product' AND ep_id = eoi_p_id -- Product conditions
AND eoi_parentid = '9'
AND po_id = eoi_po_id

help optimizing query (shows strength of two-way relationships between contacts)

i have a contact_relationship table that stores the reported strength of a relationship between one contact and another at a given point in time.
mysql> desc contact_relationship;
+------------------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+-----------+------+-----+-------------------+-----------------------------+
| relationship_id | int(11) | YES | | NULL | |
| contact_id | int(11) | YES | MUL | NULL | |
| other_contact_id | int(11) | YES | | NULL | |
| strength | int(11) | YES | | NULL | |
| recorded | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+------------------+-----------+------+-----+-------------------+-----------------------------+
now i want to get a list of two-way relationships between contacts (meaning there are two rows, one with contact a specifying a relationship strength with contact b and another with contact b specifying a strength for contact a -- the strength of the two-way relationship is the smaller of those two strength values).
this is the query i've come up with but it is pretty slow:
select
mrcr1.contact_id,
mrcr1.other_contact_id,
case when (mrcr1.strength < mrcr2.strength) then
mrcr1.strength
else
mrcr2.strength
end strength
from (
select
cr1.*
from (
select
contact_id,
other_contact_id,
max(recorded) as max_recorded
from
contact_relationship
group by
contact_id,
other_contact_id
) as cr2
inner join contact_relationship cr1 on
cr1.contact_id = cr2.contact_id
and cr1.other_contact_id = cr2.other_contact_id
and cr1.recorded = cr2.max_recorded
) as mrcr1,
(
select
cr3.*
from (
select
contact_id,
other_contact_id,
max(recorded) as max_recorded
from
contact_relationship
group by
contact_id,
other_contact_id
) as cr4
inner join contact_relationship cr3 on
cr3.contact_id = cr4.contact_id
and cr3.other_contact_id = cr4.other_contact_id
and cr3.recorded = cr4.max_recorded
) as mrcr2
where
mrcr1.contact_id = mrcr2.other_contact_id
and mrcr1.other_contact_id = mrcr2.contact_id
and mrcr1.contact_id != mrcr1.other_contact_id
and mrcr2.contact_id != mrcr2.other_contact_id
and mrcr1.contact_id <= mrcr1.other_contact_id;
anyone have any recommendations of how to speed it up?
note that because a user may specify the strength of his relationship with a particular user more than once, you must only grab the most recent record for each pair of contacts.
update: here is the result of explaining the query...
+----+-------------+----------------------+-------+----------------------------------------------------------------------------------------+------------------------------+---------+-------------------------------------+-------+--------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------------+-------+----------------------------------------------------------------------------------------+------------------------------+---------+-------------------------------------+-------+--------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 36029 | Using where |
| 1 | PRIMARY | <derived4> | ALL | NULL | NULL | NULL | NULL | 36029 | Using where; Using join buffer |
| 4 | DERIVED | <derived5> | ALL | NULL | NULL | NULL | NULL | 36021 | |
| 4 | DERIVED | cr3 | ref | contact_relationship_index_1,contact_relationship_index_2,contact_relationship_index_3 | contact_relationship_index_2 | 10 | cr4.contact_id,cr4.other_contact_id | 1 | Using where |
| 5 | DERIVED | contact_relationship | index | NULL | contact_relationship_index_3 | 14 | NULL | 37973 | Using index |
| 2 | DERIVED | <derived3> | ALL | NULL | NULL | NULL | NULL | 36021 | |
| 2 | DERIVED | cr1 | ref | contact_relationship_index_1,contact_relationship_index_2,contact_relationship_index_3 | contact_relationship_index_2 | 10 | cr2.contact_id,cr2.other_contact_id | 1 | Using where |
| 3 | DERIVED | contact_relationship | index | NULL | contact_relationship_index_3 | 14 | NULL | 37973 | Using index |
+----+-------------+----------------------+-------+----------------------------------------------------------------------------------------+------------------------------+---------+-------------------------------------+-------+--------------------------------+
You are losing a lot lot lot of time selecting the most recent record. 2 options :
1- Change the way you are stocking data, and have a table with only recent record, and an other table more like historical record.
2- Use analytic request to select the most recent record, if your DBMS allows you to do this. Something like
Select first_value(strength) over(partition by contact_id, other_contact_id order by recorded desc)
from contact_relationship
Once you have the good record line, I think your query will go a lot faster.
Scorpi0's answer got me to thinking maybe I could use a temp table...
create temporary table mrcr1 (
contact_id int,
other_contact_id int,
strength int,
index mrcr1_index_1 (
contact_id,
other_contact_id
)
) replace as
select
cr1.contact_id,
cr1.other_contact_id,
cr1.strength from (
select
contact_id,
other_contact_id,
max(recorded) as max_recorded
from
contact_relationship
group by
contact_id, other_contact_id
) as cr2
inner join
contact_relationship cr1 on
cr1.contact_id = cr2.contact_id
and cr1.other_contact_id = cr2.other_contact_id
and cr1.recorded = cr2.max_recorded;
which i had to do twice (second time into a temp table named mrcr2) because mysql has a limitation where you can't alias the same temp table twice in one query.
with my two temp tables created my query then becomes:
select
mrcr1.contact_id,
mrcr1.other_contact_id,
case when (mrcr1.strength < mrcr2.strength) then
mrcr1.strength
else
mrcr2.strength
end strength
from
mrcr1,
mrcr2
where
mrcr1.contact_id = mrcr2.other_contact_id
and mrcr1.other_contact_id = mrcr2.contact_id
and mrcr1.contact_id != mrcr1.other_contact_id
and mrcr2.contact_id != mrcr2.other_contact_id
and mrcr1.contact_id <= mrcr1.other_contact_id;