I have a query that requires what I think is a complicated JOIN. I have three tables that are sort of "children" of each other. The top table is "clan_members". The next is "roster_members" which gets the clan_member id. The bottom one is "match_players" which gets the roster_members id. I wrote a loop that takes me through all of the results in the clan_members table. What I want to do is find out how many matches that clan member has played in. Here's the layouts of the three tables:
[clan_members]
-id
- member_id
-join_date
[roster_members]
- id
- clan_member_id
- title
[match_players]
- id
- roster_member_id
- match_id
I have never done a JOIN with three different tables before and I have no idea what order to do them in. I would greatly appreciate it if someone could write me a query!
This query will get you the number of matches that clan member with id 123 has participated in:
select count(*) as match_count
from clan_members c, roster_members r, match_players m
where c.member_id = r.clan_member_id
and r.id = m.roster_member_id
and c.id = 123
On a side note, it would be good practice to name your columns consistently. For example, all columns that have the clan_member_id should be named the same. In the clan_members table its called id but in the roster_members table its called clan_member_id. Just makes it easier to understand how the tables join together.
SELECT DISTINCT match_id
FROM clan_members
INNER JOIN roster_members
ON clan_members.id = roster_members.clan_member_id
INNER JOIN match_players
ON roster_members.id = match_players.roster_member_id;
will get you the # of unique match_ids when all three tables are joined.
Related
Hello guys this my first Q in stackoverflow so i'll be clear with you i'm very new to php so take it easy on me .
right so what am trying to do is i have 5 tables where's the relation have already been set
and i'm trying to show the related categorys and platforms using the game id note that the category has a table on it own and so as the platform then there's two other tables which have the game id and the cat id together and same as for the platform and the game and the field i have in the games table are:
id-->for the game id
name-->for the name of the game
details and image.
and in the game_cat:
g_id and cat_id
then thers the table for the category which has the name and id
and the same for the platform . these are my tables which i'm trying to select from
enter image description here
and my sql is:
SELECT games.*,
game_cat.*,
category.*
FROM games,
game_cat,
category
WHERE games.id='game_cat.g_id'
AND game_cat.g_id='game_cat.cat_id'
AND game_cat.cat_id='category.id'
but it doesn't work on phpmyadmin sql so I've done some research and there's something called join in sql which i'm not familiar with.
any help is appreciated.
Don't use single quotes for column name (when need use eventually backtics)
Use inner join if you have alway columns match (otherwise you left join ) and you can use alias for a compact query
(i have added also the last two tables ...hope the related columns name are right)
SELECT g.*,gc.*,c.* , gp.*, p.*
FROM games g
INNER JOIN game_cat gc on g.id = gc.g_id
INNER JOIN category c on gc.cat_id=c.id
INNER JOIN game_platform gp on g.id = gp.g_id
INNER JOIN platform p on gp.paltform_id=p.id
You need to JOIN between the tables based on the foreign-key relationship between them (if you don't know what this is, go read up on it!). Something like this (I don't know what columns represent the foreign keys, so making this up):
SELECT games.*,
game_cat.*,
category.*
FROM games g
INNER JOIN game_cat gc on (g.game_id = gc.g_id)
INNER JOIN category c on (gc.cat_id = c.cat_id)
WHERE games.id='game_cat.g_id'
AND game_cat.g_id='game_cat.cat_id'
AND game_cat.cat_id='category.id';
This looks like a standard implementation of a many-to-many relationship between games and category - would that be correct?
I have 3 tables for data of divisions, districts and police_stations table. The table data are dependent like
divisions
- districts
-- police_stations
Table format are
divisions
id
name
districts
id
division_id
name
police_stations
id
division_id
district_id
name
Can I design just one table with all of my tables data with current table dependency? If I can, how will be the traversing process?
To group multiple tables together, you should use JOINS. This is a better database practice than creating new tables.
The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns in both tables.
SELECT *
FROM divisions divis
INNER JOIN districts dis
ON dis.division_id = divis.id
INNER JOIN police_stations pol
ON pol.district_id = dis.id
Note: Apparently the DIV keyword is reserved in mysql, so you you have to use something else to identify divisions.
If you insist on creating a new table with this data, you can use the CREATE TABLE AS recipe.
In order to do this though, we need to modify our original schema. New tables cannot have duplicate names, so we have to change the original tables to all have unique columns.
For example name becomes district_name.
CREATE TABLE combined AS (
SELECT divis.id, divis.division_name, dis.district_name, pol.police_name
FROM divisions divis
LEFT JOIN districts dis
ON divis.id = dis.division_id
LEFT JOIN police_stations pol
ON pol.district_id = dis.id
);
Here is a fiddle to demonstrate it
http://sqlfiddle.com/#!9/7ec3b/1/0
This is really bad database design though. My first solution is recommended
Using a single table: There would be an id for uniquely identifying each row; it would be the PRIMARY KEY. There would be a parent_id to say which other row is its 'parent' (division is parent of district, etc).
The JOIN becomes a self join.
SELECT ...
FROM tbl AS division
JOIN tbl AS district ON division.id = district.parent_id
JOIN tbl AS station ON district.id = station.parent_id
WHERE ...
Be sure to 'qualify' each field in the SELECT and WHERE with the appropriate 'alias'; example: division.name.
This design pattern works for most 'hierarchical' structures of arbitrary depth. Yours is exactly 3 levels deep, so it is somewhat simpler.
Note that the parent_id would be 0 for any "district" rows. And it would be useful to have INDEX(parent_id).
Hopefully it solves your problem
SELECT * from divisions d
join police_stations ps on d.id=ps.division_id
join districts dist on ps.district_id =dist.id;
I have 3 sql tables
1) a table with headers of a coupon - id of this equals the id of the second table
2) a tables with details of the coupon - user_id on this tables equals user id of the third table
3) a table with details of user
So far I have this query
"SELECT kpn_processed_deals.kpn_id,
kpn_processed_deals.purchased_date, kpn_processed_deals.claim,
kpn_processed_deals.uid,kpn_deal_headers.kpn_type,
kpn_deal_headers.title,kpn_deal_headers.created_by
FROM kpn_processed_deals INNER JOIN kpn_deal_headers ON
kpn_processed_deals.kpn_id = kpn_deal_headers.kpn_id AND
kpn_deal_headers.created_by = '$var'";
This works just fine but I want to get the value of the users email on the third table using a join but I have been unsuccessful so far. Sorry if my formatting is messy. I'm horrible at these things.
Just add another JOIN.
"SELECT p.kpn_id, p.purchased_date, p.claim, p.uid,h.kpn_type, h.title, h.created_by, u.email
FROM kpn_processed_deals AS p INNER
JOIN kpn_deal_headers AS h ON p.kpn_id = h.kpn_id
JOIN kpn_deal_users AS u ON u.user_id = p.user_id
WHERE h.created_by = '$var'";
Also notice the use of table aliases, so you don't have to repeat the verbose table names throughout the query.
And constraints on single tables should normally be in the WHERE clause; the ON clause is for conditions related to joining the tables (an exception is in outer joins, where constraints on the child table need to be in the ON clause as well).
We are doing some pro bone work for a good cause and I'm having a hell of a time with a query. The coding has been done by many volunteers over the years which has an inevitable outcome.
I have two tables, A and B. What I need is a sum of of score_hours on a join between the two where the data is unique for each instance of only A.
Please keep in mind that both tables are quite big (10 to 50k+ each depending on time in the month).
Table A:
id (pk, ai)
uid (int)
scores_date (timestamp (but for some reason only the actual date, not
the time))
score_hours (decimal 3,1)
Table B:
id (pk, ai)
uid (int)
shift_date (timestamp)
There are many records in table B that have the uid we are looking for on several dates (the dates are not unique). Table A has multiple records for uid but on different days. So it could have 1 uid a day, but not 2 instances of 1 uid a day.
There are obviously more selectors for both tables, but they don't match in any way between the tables (although I do need to query them with simple "AND") so this is what I have to work with. I do need to join them because of the rest of the query, but so far I'm not getting the records I need within a decent time.
My attempts were:
This almost made it. But the execution time was disgusting and failed with some simple selectors.
SELECT SUM(score_hours)
FROM A
WHERE
A.uid IN
(SELECT B.uid
FROM B
WHERE B.uid = "1")
This gives the right output but it joins one for every instance of a uid. Normally you can solve that by grouping, but the sum will still count all. So that is not an option:
SELECT SUM(score_hours)
FROM A
LEFT JOIN B ON A.uid = B.uid
WHERE A.uid = "1"
*edit: Not only do I need to JOIN on uid, but there has to be something like this in it:
DISTINCT(date(m.shift_datum)) = DATE(d.dagscores_date)
It is actually a very basic query, except for the fact that a SUM is needed on a record which is not unique in regards to the Left join and that I need to JOIN on two tables at the same time.
If you need more data please tell me so. I can provide all.
You need to remove the duplicates from the table you're joining with, otherwise the cross-product creates multiple rows that get added into the sum.
SELECT SUM(score_hours)
FROM A
JOIN (SELECT DISTINCT uid
FROM B) AS B
ON A.uid = B.uid
I have a query I need to perform on a table that is roughly 1M records. I am trying to reduce the churn, but unfortunately there is a UNION involved (after i figure this join out), so that may be a question for another day.
The records and data I need to get reference 3 fields in a table that need each pull a description from another table and return it in the same record, but when i do the Inner join i was thinking, it either returns only 1 field fromt he other table, or multiple records from he original table.
Here are some screen shots of the tables and their relationship:
Primary table containing records (1 each) with the physician record I want to pull, including up to 3 codes that can be listed in the "taxonomy" table.
Secondary table containing records (1 each) with the "Practice" field I want to pull.
A Quick glance of the relationship i'm talking about
I presume that if perform an inner join matching the 3 fields in the physicians table, that it will have to iterate that table multiple times to pull each taxonomy code .. but I still can't even figure the syntax to easily pull all of these codes instead of just 1 of them.
i've tried this:
SELECT
taxonomy_codes.specialization,
physicians.provider_last_name,
physicians.provider_first_name,
physicians.provider_dba_name,
physicians.legal_biz_name,
physicians.biz_practice_city
FROM
taxonomy_codes
INNER JOIN physicians ON physicians.provider_taxonomy_code_1 = taxonomy_codes.taxonomy_codes OR physicians.provider_taxonomy_code_2 = taxonomy_codes.taxonomy_codes OR physicians.provider_taxonomy_code_3 = taxonomy_codes.taxonomy_codes
First, the query churns a lot and it only returns one taxonomy specialty result which I presume is because of the OR in the join statement. Any help would be greatly appreciated.
Thank you,
Silver Tiger
You have to join the taxonomy_codes table multiple times:
SELECT p.provider_last_name, p...., t1.specialization as specialization1, t2.specialization as specialization2, t3.specialization as specialization3
FROM physicians p
LEFT JOIN taxonomy_codes t1 ON t1.taxonomy_codes = provider_taxonomy_code_1
LEFT JOIN taxonomy_codes t2 ON t2.taxonomy_codes = provider_taxonomy_code_2
LEFT JOIN taxonomy_codes t3 ON t3.taxonomy_codes = provider_taxonomy_code_3