How to join two tables using different ID but are related - php

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.

Related

Create table report from joining table in MySQL

I have a proble with my query, i have to create report but there is no same data.
here is my database https://www.db-fiddle.com/f/2bA7StrBpz18tLFgAQh2QV/1
and this is my query example but the result is wrong :
SELECT
a.IdBukti,c.LineName,a.LineID,a.Tanggal,b.TypeProduksi AS partnamemonthly,a.PartID AS partmonthly,a.QtyPlanning AS qtymonthly,
d.partnamedaily,d.partiddaily,d.qtydaily
FROM
trans_ppicbdt_dt a
INNER JOIN ms_part b ON b.PartId = a.PartID
INNER JOIN ms_line c ON c.LineID = a.LineID
INNER JOIN(SELECT
c.LineName,
a.LineID,
a.Tanggal,
b.TypeProduksi AS partnamedaily,
a.PartID AS partiddaily,
a.QtyPlanning AS qtydaily
FROM
trans_ppich a
INNER JOIN ms_part b ON b.PartId = a.PartID
INNER JOIN ms_line c ON c.LineID = a.LineID
WHERE
a.Tanggal = '2018-04-11' AND a.DivisiId='DI070' AND a.IdLocation='1'
GROUP BY
a.LineID,
a.PartID) d on d.LineID=a.LineID AND d.Tanggal=a.Tanggal
WHERE
a.Tanggal = '2018-04-11' AND a.DivisiId='DI070' AND a.IdLocation='1'
GROUP BY
a.LineID,
a.PartID
So i have 2 data, first monthlyplan and second daily plan.
And i want the result like this
Can you help me to create the report in one single query
It's easier (for me) to figure out how to formulate a query if I can see the relations in a glance. Here's how Yours would look:
(monthly) (daily)
trans_ppicbdt_dt ms_line trans_ppich
---------------- ----------- --------------
IdUnik (primary) ----> LineID <---- IdBukti (FK)*
LineID ------------/ \--- LineID
There are some problems with your structure that need to be fixed at the earliest opportunity:
ms_line needs a primary key. lineID should work if it is unique. (no such luck, it is not unique)
trans_ppich needs a primary key. IdBukti is a foreign key to yet another table.
There needs to be an index on lineID in all tables.
Tables need to be normalized. You shouldn't have to repeat data over several lines.
Nevertheless, we can still get to where you want to go. Now that I can see the relation, the query is really rather simple in theory, but I don't have all the required tables and fields:
SELECT DISTINCT line.LineName,
monthly.{unknown field} as monthlyPartName,
monthly.PartID as monthlyPartID,
monthly.{unknown field} as monthlyProcess,
monthly.{unknown field} as monthlyQty,
daily.{unknown field} as dailyPartName,
daily.PartID as dailyPartID,
daily.{unknown field} as dailyQty,
{unknown table}.{unknown field} as remarks
FROM ms_line as line
LEFT JOIN trans_ppicbdt_dt AS monthly ON line.lineID=monthly.lineID
LEFT JOIN trans_ppich AS daily ON line.lineID=daily.lineID
WHERE
{your where clause to filter results}
The way this works is it iterates through the (distinct) line items, and looks for a match in the monthly table (left join monthly). If there is a match, it adds the values. If there isn't a match, it simply adds null for values. Then it does the same for the daily table: if there is a match, it adds the values, otherwise it simply gives null for all daily values.
This will fall apart, however, if lineID is duplicated in rows of the monthly and daily tables.
I don't know where the remarks come from, so that is left as an exercise for you. :)

Get CSV from query which involves multiple tables

I'm trying to make a query to extract elements from 2 tables, which are linked via another table.
So I have 3 tables:
authors
- id, name, book
category
- id, name, description
category-author
- id, idauthor, idcategory
Now I want to make a query to make the following output:
row: authors.id, authors.name, authors.book, category.name
I don't know what category's are linked using the 2 tables only, so I need to use the last one, the category-author table. The id's of both the author and the category are linked via that table.
I got the following query:
SELECT authors.id, authors.name, authors.book, category.name FROM category, author LEFT JOIN SELECT ??
I'm stuck at the remaining part of the query.
Also when I have this query, can I just extract a CSV with phpmyadmin?
You can get related information from different tables using table joins. Relations between tables should be specified using foreign keys (i.e. the column idcategory from category-author is presumably a foreign key that refers to primary key column category.id). In a join clause, you merely specify which tables are to be joined and on what column:
SELECT table1.col1, table2.col2
FROM table1
JOIN table2 ON table1.pkCol = table2.fkCol
This means you can't specify any SELECT or FROM clauses within a JOIN clause. The columns you wish to select from joined tables are all specified in the initial SELECT statement, and you only specify one table in the FROM clause, from which you subsequently perform the table joins.
In your case, I think this should get you started:
SELECT authors.id, authors.name, authors.book, category.name
FROM category
LEFT JOIN category-author ON category-author.idcategory = category.id
LEFT JOIN authors ON authors.id = category-author.idauthor
I'm not sure how familiar you are with foreign keys, primary keys and table joins, so I won't elaborate any more on this. I think specifying multiple tables in a FROM clause is bad practice, even if your database system still supports it (Related question).
From then on, you can easily export the results from within PhpMyAdmin, as there is an export button for every table overview, including query results.

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.

Double query with WHERE IN, or join

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

PHP Mysql select query from multiple tables

I have 2 tables. The parent table is learn_more and child table is reference_keys
Both tables are innodb
reference_keys has two columns:
key_id [index]
key_href
learn_more table
id [primary]
keys_id [foreign key]
page_title
page_content
What I am trying to do is get multiple links in the learn more table from the reference_keys table.
So example, learn_more table id:1, keys_id:1,3,4,8,13,25,..., page_title:Home Page: blah blah, page_content: blah blah......
The problem is that phpmyadmin will not allow me to put more than 1 id in the keys_id of learn_more.
//ERROR
//Warning: #1265 Data truncated for column 'keys_id' at row 1
I'm guessing the relation view is not setup correctly. - How do i fix this?
and on my page it shows the key_id in the echo instead of the value for the id: which is the key_href. so my page show "1" instead of the value for 1 which is a link..
Perhaps my sql query is not correct?
$SQL = "SELECT * FROM learn_more WHERE page_title = '$this_page'";
To build a many-to-many here is what you could do:
reference_keys has two columns:
key_id [index]
key_href
learn_more_to_reference_key
reference_key_id [FK to reference_keys]
learn_more_id [FK to learn_more]
learn_more table
id [primary]
page_title
page_content
Then you have essentially a 1:N on each side of the relationship. Notice that I removed the FK from the learn_more table, too.
So to grab the relationship you'd query like this:
SELECT * FROM Learn_More lm
INNER JOIN learn_more_to_reference_key lmtrk ON lm.id = lmtrk.learn_more_id
INNER JOIN reference_keys rk ON rk.id = lmtrk.reference_key_id
I believe the inner join is correct, i'm double-checking that.
If you want to have one row in learn_more correspond to multiple rows in reference_keys, you need to move the foreign key field from the learn_more table to the reference_keys table.
So instead of having a foreign key field in learn_more that points out to multiple rows of reference_keys (which, as you seem to be running into, is not supported), you have the multiple rows of reference_keys all point back to the learn_more table.
This would implement a one-to-many relationship between learn_more and reference_keys. If you need a many-to-many relationship (where each reference_key rows can be connected to many learn_more rows and vice-versa) you need to use a third table to establish a link between the two databases. See http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php for more information.
You're getting the keys_id because that is what is in the learn_more table. To get the key_href, you'll need to JOIN the learn_more table to the reference_keys table.
Also, #ametren is correct - you should have a many-to-many table that links your two current tables.
key_linking_table
id [primary and foreign key]
keys_id [primary and foreign key]
$SQL =
"SELECT lm.id, lm.page_title, lm.page_content, rk.key_href
FROM learn_more AS lm
LEFT JOIN key_linking_table AS klt
ON klt.id = rk.id
LEFT JOIN reference_keys AS rk
ON klt.key_id = rk.key_id
WHERE [condition]"

Categories