Combining two MySQL tables yet want one column to equal another - php

I am trying to join two tables together in a view. My first table combines two tables but now I am trying to join that table to a second table. I am trying to use a join to make sure the second table which contains roles which are performed by the user, matches up with the first table but if there are no records in the second table, I still want all the records from table 1. I know my explanation is a little confused, so my code is as follows:
CREATE VIEW `data` AS SELECT
`information`.`username`, `information`.`department`,
`information`.`company`, `information`.`title`,
`information`.`internal_number` AS `user_internal_phone`,
`information`.`external_number`AS `user_external_phone`,
`information`.`mail`, `information`.`cn` AS `name`, `information`.`hours`,
`information`.`languages`, `information`.`functions`,
`information`.`service` AS `contact_point_name_one`,
`information`.`subservice` AS `contact_point_name_two`,
`information`.`internal_phone` AS `contact_internal_phone`,
`information`.`external_phone` AS `contact_external_phone`,
`information`.`keywords`, `information`.`description`,
`information`.`provided_by`, `information`.`id`,
GROUP_CONCAT(`staff_roles`.`role` SEPARATOR ', ') AS `roles`,
`staff_roles`.`user`
FROM `information`
CROSS JOIN `staff_roles` ON `information`.`username` = `staff_roles`.`user`;
I get an error when I do an outer join and a cross join and an inner join both return rows where there is a row in both tables yet I want it to display the rows where there is nothing in the second table as well. The purpose of using a join is so that, where there is a match, the row from table 2 should match the row on table 1

Use LEFT JOIN. The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.
Just replace your CROSS JOIN with LEFT JOIN

Simply use LEFT JOIN instead of CROSS JOIN:
CREATE VIEW `data` AS SELECT
...
FROM `information`
LEFT JOIN `staff_roles` ON `information`.`username` = `staff_roles`.`user`;
Take a look at http://www.w3schools.com/sql/sql_join_left.asp for further details about why LEFT JOIN.

Related

Joining tables based on reference table value

Have these tables
and given post_map.tag_id='1', I would like to get:
entity_type table determines what table be look in, i.e. what table entity_id is stored in. My main goal is to get this table as the result of either mysqli::multi_query() or mysqli::query(), i.e. without PHP going back and forth to the database multiple times; this table may have many many rows and getting this table at once would much more efficient.
My attempts thus far:
I have tried JOIN clause but I don't know how to use the row value of prior SELECT as the table name for the JOIN clause.
Tried Prepared Statments but can't form anything usable.
It can be done by IF() and JOIN. I have solution for you, run below query...
SELECT et.type,
IF(et.type='resource',r.resource_type_id,NULL) AS resource_type_id,
IF(et.type='resource',r.value,NULL) AS value,
IF(et.type='user',u.name,NULL) AS name,
IF(et.type='link',l.source,NULL) AS source,
IF(et.type='link',l.count,NULL) AS count
FROM `post_map` as pm
JOIN `entity_type` as et ON pm.entity_id = et.id
LEFT JOIN `resource` as r ON pm.entity_type_id=r.id
LEFT JOIN `user` as u ON pm.entity_type_id=u.id
LEFT JOIN `link` as l ON pm.entity_type_id=l.id
WHERE pm.tag_id='1'

php and mysql queries

I'm creating a website where the user can add some information about multiple computers into a database.
In the mysql database I have 3 tables. TypeOfMachine, Software and Hardware. The only common thing they have is the NumberOfMachine.
I must create a page where the user can run reports showing devices that have a specific piece of software installed (user specified) or specific hardware (user specified) after he submitted the computer's info.
Any ideas how I can do this?
And how I can connect all 3 tables into one?
I thought about this code but i dont know what to put in WHERE. I have 10 variables. and I have to show all the computers with what the user has asked and their info as well!
$search1 = "
SELECT
TypeOfMachine.NumberOfMachine, TypeOfMachine.TypeOfMachine, TypeOfMachine.OS, Software.Software1, Software.Software2, Software.Software3, Hardware.SSD, Hardware.Harddisk, Hardware.MonitorSize, Hardware.Ram, Hardware.Rom, Hardware.Processor
FROM TypeOfMachine, Software, Hardware
WHERE
but i
You want to use a join. This example is based on the fact that you've said the NumberOfMachine field is present in all tables and is a common link between them:
SELECT
TypeOfMachine.NumberOfMachine,
TypeOfMachine.TypeOfMachine,
TypeOfMachine.OS,
Software.Software1,
Software.Software2,
Software.Software3,
Hardware.SSD,
Hardware.Harddisk,
Hardware.MonitorSize,
Hardware.Ram,
Hardware.Rom,
Hardware.Processor
FROM TypeOfMachine
LEFT JOIN Software
ON Software.NumberOfMachine = TypeOfMachine.NumberOfMachine
LEFT JOIN Hardware
ON Hardware.NumberOfMachine = TypeOfMachine.NumberOfMachine
WHERE
...
It's general question, I don't know which tables contains a spesific columns as indicator for all tables. It's about inner and outer join:
The two common types of joins are an inner join and an outer join. The difference between an inner and outer join is in the number of rows included in the results table.
Inner join: The results table produced by an inner join contains only rows that existed in both tables.
Outer join: The combined table produced by an outer join contains all rows that existed in one table with blanks in the columns for the rows that did not exist in the second table.
For instance, if table1 contains a row for Joe and a row for Sally, and table2 contains only a row for Sally, an inner join would contain only one row: the row for Sally. However, an outer join would contain two rows — a row for Joe and a row for Sally — even though the row for Joe would have a blank field for weight.
The results table for the outer join contains all the rows for one table. If any of the rows for that table don’t exist in the second table, the columns for the second table are empty. Clearly, the contents of the results table are determined by which table contributes all its rows, requiring the second table to match it.
Two kinds of outer joins control which table sets the rows and which must match: a LEFT JOIN and a RIGHT JOIN.
You use different SELECT queries for an inner join and the two types of outer joins. The following query is an inner join:
SELECT columnnamelist FROM table1,table2
WHERE table1.col2 = table2.col2
And these queries are outer joins:
SELECT columnnamelist FROM table1 LEFT JOIN table2
ON table1.col1=table2.col2
SELECT columnnamelist FROM table1 RIGHT JOIN table2
ON table1.col1=table2.col2
In all three queries, table1 and table2 are the tables to be joined. You can join more than two tables. In both queries, col1 and col2 are the names of the columns being matched to join the tables. The tables are matched based on the data in these columns. These two columns can have the same name or different names, but they must contain the same type of data.
For general concept you can use #Scrowler suggestion, or this one:
http://stackoverflow.com/questions/1204217/mysql-select-join-3-tables

MySQL Inner Join involving three tables

I am working with four tables:
query,
store,
cluster_group,
tv_region
I want to retrieve query records belonging to a particular TV Region record.
A query record either belongs to a record in the store or cluster_group tables. The query table has 'store_id' and 'cluster_group_id' columns. Either will be null whilst the other will refer to a record in the store or cluster_group table. The store and cluster_group tables both have a 'tv_region_id' column.
To retrieve query records that belong to a TV Region record that has an id = 2, I wrote the following SQL statement:
SELECT query.id AS query_id, cluster_group.name as cluster_name, cluster_group.tv_region_id as cluster_tv_region, store.store_name
FROM query
INNER JOIN cluster_group
ON cluster_group.id=query.cluster_group_id
INNER JOIN store
ON store.id=query.store_id
WHERE cluster_group.tv_region_id = 2
AND store.tv_region_id = 2;
The problem is that it returns zero records even though there are query records that belong to the specified TV Region (via a cluster group or store record). I may have misunderstood how 'inner join' works.
I'm working with Doctrine 2 and have attempted the query using the left join but it still returns nothing, I guess this is because its returning null values too. How do I get it to return only the query records I am interested in and no null values?
Appreciate if someone can point me in the right direction to retrieve the relevant query records.
You will need to use OUTER joins, or possibly LEFT
INNER joins will only return data where there is a matching record on both sides. As you state in your question you only get a match on one side or the other, therefore there is never going to be a matching record across both store and cluster
Jeff Atwood has a good explanation of the join types on his blog http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
Try this:-
SELECT query.id AS query_id, cluster_group.name as cluster_name, cluster_group.tv_region_id as cluster_tv_region, store.store_name
FROM query
LEFT OUTER JOIN cluster_group
ON cluster_group.id=query.cluster_group_id
AND cluster_group.tv_region_id = 2
LEFT OUTER JOIN store
ON store.id=query.store_id
AND store.tv_region_id = 2
EDIT - no experience of doctrine, but you could try using a UNION:-
SELECT query.id AS query_id, cluster_group.name as cluster_name, cluster_group.tv_region_id as cluster_tv_region, NULL AS store_name
FROM query
INNER JOIN cluster_group
ON cluster_group.id=query.cluster_group_id
AND cluster_group.tv_region_id = 2
UNION
SELECT query.id AS query_id, NULL as cluster_name, NULL as cluster_tv_region, store.store_name
FROM query
INNER JOIN store
ON store.id=query.store_id
AND store.tv_region_id = 2
It works like this for me:
from table1 inner join table2 on table1.id = table2.id
inner join table3 on table1.id = table3.id

Join mysql with multiple queries

I have three different SQL tables I need to join:
table "internet" with columns id|type|status
table "type_list" with columns id|type_name
table "status_list" with columns id|status_name
I want to output text from the two other tables (type_list, status_list) but not values as numbers which currently I have in table "internet".
I also don't want to make lazy programming - PHP array to make ID's equal to something like
$type_list = array("1"=>"VDSL2","2"=>"ADSL");
$status_list = array("1"=>"Pending","2"=>"Active");
because the text is already in the tables, i just dont know how to join them and output the text as query combined together in one query.
Use JOIN
SELECT i.id, type_name, status_name
FROM internet i
LEFT OUTER JOIN type_list t ON t.id = i.type
LEFT OUTER JOIN status_list s ON s.id= i.status
Read the MySQL doc for more informations.
Just write the select with the fields you want.
select internet.id,type_name,status_name from internet
inner join type_list
on type_list.id=internet.id
inner join status_list
on status_list.id=internet.id
For this you need a LEFT JOIN, like so:
SELECT i.id, t.type_name, s.status_name
FROM internet AS i
LEFT JOIN type_list AS t ON t.id = i.id
LEFT JOIN status_list AS s ON s.id= i.id
From your question, it is unclear what field you would like to join the queries on. In the above example, the queries are joined on the id field.
Please also note that the AS is not actually necessary, I have just put it in there to make it clear what is going on

mysql join select explained

I have two tables: 'posts' and 'users' every post has a 'ref_id' column to get the user id who posted it.
Now, I am getting posts this way:
$this->db->query("SELECT * FROM posts WHERE time > '$timeLimit' LIMIT 50");
I can't understand how to join every result to get the poster related data as well. What I am doing right now is basically a loop inside a loop, where foreach of the result, get their user info. But it is pretty obvious that this is very wrong,
Apparently I need to start using joins, but how does one do it? this should be a really simple example to work with, I suppose.
Any help? Thank you.
SELECT posts.*, users.*
FROM posts
INNER JOIN users
ON posts.posted_by = users.id;
Like this:
SELECT
posts.*,,
users.Username
FROM posts
INNER JOIN users ON posts.ref_id = users.user_id;
Explanation:
To JOIN to any tables with each others, there are two things; the JOIN type and the join condition. There are three main types of join:
INNER JOIN, only the rows that match the join condition will be returned from the two tables no more rows. But:
LEFT OUTER JOIN, when you join two tables you will have one on the left of the join keyword and the other one will be in the right:
FROM Table1 <------------- This is the left table.
LEFT OUTER JOIN table2 .... <------------- This is the right table.
In LEFT OUTER JOIN the unmatched rows from the left table will be included in the result set.
RIGHT OUTER JOIN the unmatched rows from the right table will be included in the result set.
CROSS JOIN this will perform a Cartesian product from the two tables.
In our query, the query will reutrn all the users from the users table only if the ref_id equal to the user_id column form the posts table.
For more information and explanations:
A Visual Explanation of SQL Joins.
Another Visual Representation of SQL Joins.
Join syntax in MySQL
SELECT user.name
FROM users
INNER JOIN posts
ON posts.ref_id == user.id
AND posts.time > 50
http://www.w3schools.com/sql/sql_join_inner.asp

Categories