Double query with WHERE IN, or join - php

We have two major mysql (innodb) tabels. Both containing millions of records.
Here is a example of our structure
-- table 1 --
primary_id
child_id
-
-- table 2 --
id
structure
contents
It's not like this, but for the question it's the same.
We need to fetch about 50.000 records from table 2, that are linked to primary id 2022.
What is the most quickly way to do this.
This is what we came up with:
1)
Do a select with a join on the two tables.
2)
Do a select of the ids in table 1 getting 200.000 records and then a select WHERE IN (all id's) and a filter on the structure there.
Any ideas?

i would go with a join. Select records from first table with the primary_id you need and join the second table on the ids

Related

How to join two tables using different ID but are related

I am trying to fetch data from the parent table using a child table but there seems to be an error I am doing while trying to implement this
I have tried to use a join statement but fail every time upon executing the statement. The code should fetch the data using the following fields:
Parent table COMPETITIONS
1. comp_id - linked to fixtures table
2. comp_name
Parent table TEAMS:
1. team_id - linked to home_teamID & away_teamID
2. team_name
3. team_email
Child table FIXTURES:
1. fixture_id
2. fixture_date
3. fixture_time
4. home_teamID - linked to the team's table [team_id]
5. away_teamID - linked to the team's table [team_id]
6. comp_id - linked to the competitions table
I tried using a join, but the error I get is that there an exception near the 'teams' clause of my "JOIN ON" syntax.
The expected results are a table that contains all the FIXTURES records which have been select or extracted from the parent tables. But the error I seem to get is that MySQL is not allowing me to access the TEAMS table using the field HOME_TEAMid and AWAY_TEAMid. However, both fields are related to the Teams table as aforementioned
How about this?
SELECT f.fixture_id, f.fixture_date, f.fixture_time,
th.team_name as Hteam_name,
th.team_email AS Hteam_email,
ta.team_name as Ateam_name,
ta.team_email as Ateam_email
FROM FIXTURES as f
LEFT JOIN TEAMS as th ON f.home_teamID = th.team_id -- HOME
LEFT JOIN TEAMS as ta ON f.home_teamID = ta.team_id -- AWAY
WHERE th.team_id = 123 -- any condition you like here
You can take advantage of table aliasing.

PHP function to return data from database as table with table relationships

I have a requirement for a PHP function that takes table or tables and the required columns from those db tables and returns a html table containing the data. I know how to do this for one table but am struggling with how to make this more dynamic
My thinking for one table would be to have a function that takes the table name and then an array of columns and then just selects the data from the table and then loops through it constructing the data as html and then return that from the function.
As an example my database has two tables; users and orders
users
|----------------------------|
|user_id|first_name|last_name|
|-------|----------|---------|
orders
|----------------------|
|order_id|user_id|total|
|--------|-------|-----|
Now with the function discussed above it would be easy to generate a table for all the users or orders but what I would like to do is have a function where I could dynamically join tables and for example list all users and the number of orders they've made or list all orders from user x. I know that this would be possible with many different functions but I'm really interested in developing a way of doing this dynamically and basically building all the relationships somehow in the program and then be able to call one function and request columns x,y and z
My thinking so far would be (again for this example) somehow define that number of orders for user i = count(order_id) where user_id = i
Hope this makes sense and thank you in advance
The INFORMATION_SCHEMA.KEY_COLUMN_USAGE table can be used to find all foreign key relationships from a particular table to other tables, e.g:
SELECT `TABLE_NAME`,
`COLUMN_NAME`,
`REFERENCED_TABLE_NAME`,
`REFERENCED_COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE`
WHERE `TABLE_SCHEMA` = SCHEMA() -- current schema
AND `REFERENCED_TABLE_NAME` IS NOT NULL
AND `TABLE_NAME` = 'orders'; -- name of table to get relationships to other tables
This should return something like the following:
+--------------+-------------+-----------------------+------------------------+
| TABLE_NAME | COLUMN_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
+--------------+-------------+-----------------------+------------------------+
| orders | user_id | users | user_id |
+--------------+-------------+-----------------------+------------------------+
The above can be done in PHP and the results can then be iterated over to dyamically construct a query that selects from those tables, joining on the listed columns. Will leave that part as an exercise ;-)
You wouldn't need to make a function to grab data from first table then loop around them and get data from the second table.
SQL can do this for you with 1 hit on the database.
All what you need to do is join the two tables, and grab the data you want..
If I understood what you need right, you want to grab all users id from the first table, and get their order count from the second table.
A simple join or selecting from both table could do that, and I suggest something like:
Select a.user_id, b.count(order_id)
FROM table1 as a, table2 as b
WHERE a.user_id = b.user_id
Group By a.user_id
Or you could join the tables and do a similar task.
I am assuming you're gonna access database from PHP code, so try that, and give me back your feedback.
This is easy to implement but we have to fix few things.
Our requirement:
1. Identify Tables according to column name.
2. How we can Join those tables.
3. How to resolve ambiguity of columns.
Solution:
Unique column name for each field or no table has duplicate column name.
To achieve it we should have fix table prefix for each table.
for example:
your column name could be odr_orderid and usr_orderid.
Now by identifying unique prefixes, we can identify tables.
Now issue arises how to join these tables
To resolve it:
Create an another table strong JOIN keys and JOin type Left, right,inner or full.
Thats all Now you can make the query as you want.

mysql select across 2 tables - only include rows from 1 if match value in another

I've built a maintenance database for a client with multiple tables that works fine, but now they want to be able to get reports and I'm having trouble creating a select statement across 2 tables.
A user can search repair type, start/end date and location...no issue at all returning results of repair type between 2 dates (all held in the same table), but the tables for different types of repair don't store the location info, that is held against info in the vehicle info table.
So on 1 table I can query something like:
SELECT fid from cm_repair where start_date >= '$date1' AND end_date <= '$date2'
and on the other table I can have:
SELECT id from cm_fleet where location='$loc'
Is there anyway I can combine these so that I only get rows where id and fid match?
You can use an INNER JOIN:
SELECT fid
from cm_repair as t1
join cm_fleet as t2 on t1.fid = t2.id and location='$loc'
where start_date >= '$date1' AND end_date <= '$date2'
Check this link.
Inner, left, and right join's are common options for combining tables that you might be needing here.
Inner will bring in all valid rows and selected columns from BOTH tables. Essentially if the ID you are joining is present in one table, but not the other, you could end up with columns with null values.
Left and right are similar and a bit faster at processing than the Inner since less data is returned (depending on your query and statements). Essentially it'll return all valid rows and selected columns from the left and right table, BUT if the ID that you are joining on is not in the other side of the join, that row of data will not be returned, therefore no null values.
Thanks, will try all this - however we've discovered a flaw in the way the tables are setup anyway and need to edit to include a location column in the repair table, so that will make it all much easier to search as well.

Searching multiple tables in MySQL database

I have several different tables in my database(mySQL).
Here are the relevant coumns for the tables
table_tournaments
tournamentId
tournamnetName
tournamentStatus
table_tournament_results
tournamentId
playerId
playerName
playerRank
tournamnetParticipants
table_players
playerId
playerName
The tournaments table contains the information about the tournament, the tournament results table shows the results from that table
I want to search the tournaments table by name and then with the returned results get the information from the tournament results table.
SELECT * FROM `tournaments` `WHERE` `tournamentName` LIKE "%Query%"
I'm not sure how to go about this, maybe I need to do something via PHP, any and all help is appreciated.
You can get the results you want with a join operation.
This is an example of an outer join, returning all rows from t that have the string 'foo' appearing as part of tournament_name, along with any matching rows from r.
A relationship between rows in the two tables is established by storing a common value in the tournamentId column of the two tables. The predicate in the ON clause specifies the condition that determines if a row "matches".
SELECT t.tournamentId
, t.tournamentName
, t.tournamentStatus
, r.playerId
, r.playerName
, r.playerRank
FROM table_tournaments t
LEFT
JOIN table_tournament_results r
ON r.tournamentId = t.tournamentId
WHERE t.tournament_name LIKE '%foo%'
ORDER
BY t.tournamentId
, r.playerId
The t and r that appear after the table names are table aliases, we can qualify references to the columns in each table by prefacing the column name with the table alias and a dot. This makes the column reference unambiguous. (In the case of tournamentId, MySQL doesn't know if you are referring to the column in t or r, so we qualify it to make it explicit. We follow this same pattern for all column references. Then, someone reading the statement doesn't need to wonder which table contains the column playerId.
Your Query may be like this
SELECT a.*, b.tournamnetName FROM table_tournament_results a
left join table_tournaments on a.tournamentId=b.tournamentId
WHERE b.tournamnetName LIKE "%Query%"

Linking tables in mysql

I need to know how to link two tables in a php/mysql set up then rank the results?
Here is my situation.
I have a stories table:
storyid
writerid
title
story
submitdate
and a votes table
voteid
userid
storyid
vote
I store a vote up as a 1 and a vote down as a -1
I am looking for a way to join these two table then rank/sort the stories by the number of votes they recieve.
I am open to any ideas about how to do so or a different possible database schema.
I prefer to keep the names of my tables singular. It's not a "Stories" table; it's a "Story" table with multiple rows.
A vote can only be attributed to a single story, so it's a one-to-many relationship between the two. I'd put the foreign key in the votes table and let it point out the story it's associated with. Change your schema if you agree: remove the voteid from the story table and make storyid in vote a foreign key to the story table.
But with that said, perhaps you can try a query like this:
select stories.storyid, sum(vote=-1) as down, sum(vote=1) as up
from stories
inner join votes on (stories.storyid = votes.storyid)
group by stories.storyid
Corrected per ypercube's comment below.

Categories